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

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


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

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


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 day5 0 * * *        /path/to/your/pythonscript

Python code:

import osif os.getenv('CRONTAB') == 'true':   # do your crontab thingselse:   # do your debug things


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.