Detect if python script is run from console or by crontab [duplicate]

我的梦境 提交于 2019-12-22 02:16:52

问题


Imagine a script is running in these 2 sets of "conditions":

  1. live action, set up in sudo crontab
  2. debug, when I run it from console ./my-script.py

What I'd like to achieve is an automatic detection of "debug mode", without me specifying an argument (e.g. --debug) for the script.

Is there a convention about how to do this? Is there a variable that can tell me who the script owner is? Whether script has a console at stdout? Run a ps | grep to determine that?

Thank you for your time.


回答1:


Since sys.stdin will be a TTY in debug mode, you can use the os.isatty() function:

import sys, os
if os.isatty(sys.stdin.fileno()):
    # Debug mode.
    pass
else:
    # Cron mode.
    pass



回答2:


You could add an environment variable to the crontab line and check, inside your python application, if the environment variable is set.

crontab's configuration file:

CRONTAB=true

# run five minutes after midnight, every day
5 0 * * *        /path/to/your/pythonscript

Python code:

import os

if os.getenv('CRONTAB') == 'true':
   # do your crontab things
else:
   # do your debug things



回答3:


Use a command line option that only cron will use.

Or a symlink to give the script a different name when called by cron. You can then use sys.argv[0]to distinguish between the two ways to call the script.



来源:https://stackoverflow.com/questions/4213091/detect-if-python-script-is-run-from-console-or-by-crontab

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