16

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.

Martin Tóth
  • 1,747
  • 3
  • 24
  • 35
  • similar to [this SO question](http://stackoverflow.com/questions/2086961/how-can-i-determine-if-a-python-script-is-executed-from-crontab) – Marcus Whybrow Nov 18 '10 at 09:04

3 Answers3

38

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
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
9

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
Simone
  • 11,655
  • 1
  • 30
  • 43
4

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.

Ber
  • 40,356
  • 16
  • 72
  • 88
  • 2
    Although I think using `os.isatty()` to detect whether `sysout` is a terminal is a hack. the OP specifically said he did not want to to do it with a command line argument. In addition, it sounds like Python itself might be doing something like this in certain situations -- see the info for the **-i** interpreter command line option in the [1.1.3. Miscellaneous options](http://docs.python.org/using/cmdline.html?highlight=command%20line%20option#miscellaneous-options) section of the online docs. – martineau Nov 18 '10 at 11:32