How can I check to see if a Python script was started interactively?

三世轮回 提交于 2019-11-29 16:15:07

You should simply add a command-line switch in the scheduled task, and check for it in your script, modifying the behavior as appropriate. Explicit is better than implicit.

One benefit to this design: you'll be able to test both behaviors, regardless of how you actually invoked the script.

If you want to know if you're reading from a terminal (not clear if that is enough of a distinction, please clarify) you can use

sys.stdin.isatty()

I'd just add a command line switch when you're calling it with cron:

python yourscript.py -scheduled

then in your program

import sys

if "-scheduled" in sys.argv:
    #--non-interactive code--
else: 
    #--interactive code--
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!