How to tell when a script is executed by cron ?

Grant Edwards grante at visi.com
Wed Feb 5 01:24:02 EST 2003


In article <pan.2003.02.05.05.20.31.693008 at scu.edu.au>, Simon Dobner wrote:
> On Wed, 05 Feb 2003 11:41:45 +1100, Simon Dobner wrote:
> 
>> I want to know how to tell if a script is being executed in the background
>> by cron, as opposed to running in the foreground from the command prompt.
> 
> OK, I had a bit of a play and came up with this
> 
> import sys
> import termios
> 
> try:
>     termios.tcgetattr(sys.stdout)
>     #this IS a terminal, therfore we are running interactivly
>     # Do nothing
> except:
>     #this is NOT a terminal so
>     logfile = open('/tmp/logfile', 'w')
>     sys.stdout = logfile

You can also use 

 if os.isatty(sys.stdout.fileno()):
      # we're running interactively
 else:
      # batch mode

-- 
Grant Edwards                   grante             Yow!  While I'm in
                                  at               LEVITTOWN I thought I'd
                               visi.com            like to see the NUCLEAR
                                                   FAMILY!!




More information about the Python-list mailing list