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

时光毁灭记忆、已成空白 提交于 2019-11-28 09:31:31

问题


I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness?

EDIT: this could either be a cron job, or started by a windows batch file, through the scheduled tasks.


回答1:


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.




回答2:


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()



回答3:


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--


来源:https://stackoverflow.com/questions/1285024/how-can-i-check-to-see-if-a-python-script-was-started-interactively

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