2

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.

Nosredna
  • 78,682
  • 15
  • 92
  • 122
Geo
  • 89,506
  • 114
  • 330
  • 511
  • 1
    "Scheduled task"? Started by what piece of software? What platform? "Manually?" From IDLE? From the Command-line? What platform? What shell? – S.Lott Aug 16 '09 at 18:50
  • Possible duplicate of [Checking for interactive shell in a Python script](https://stackoverflow.com/questions/6108330/checking-for-interactive-shell-in-a-python-script) – ideasman42 Aug 29 '17 at 06:07

3 Answers3

11

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.

Ned Batchelder
  • 345,440
  • 70
  • 544
  • 649
7

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()
cobbal
  • 68,517
  • 19
  • 142
  • 155
0

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--
gct
  • 13,568
  • 14
  • 63
  • 94