2

I have a Python script that normally runs out of cron. Sometimes, I want to run it myself in a (Unix) shell, and if so, have it write its output to the terminal instead of writing to a log file.

What is the pythonic way of determining if a script is running out of cron or in an interactive shell (I mean bash, ksh, etc. not the python shell)?

I could check for the existence of the TERM environment variable perhaps? That makes sense but seems deceptively simple...

Could os.isatty somehow be used?

I'm using Python 2.6 if it makes a difference. Thanks!

1
  • 1
    Yes, os.isatty works fine. Just pass it os.isatty(sys.stdout.fileno()). Or, more simply, use the isatty method on stdout itself. Commented Feb 27, 2013 at 20:20

2 Answers 2

5

You can check whether your stdout is attached to a terminal:

import sys
sys.stdout.isatty()

You can do it with os.isatty, but that requires a file descriptor, which is less straightforward:

import os
os.isatty(sys.stdout.fileno())
Sign up to request clarification or add additional context in comments.

Comments

2

If you really need to check this, Pavel Anossov's answer is the way to do it, and it's pretty much the same as your initial guess.

But do you really need to check this? Why not just write a Python script that writes to stdout and/or stderr, and your cron job can just redirect to log files?

Or, even better, use the logging module and let it write to syslog or whatever else is appropriate and also write to the terminal if there is one?

2 Comments

redirect doesn't quite work, because many scripts write to a common logfile (yes, I could redirect with append but...) However, I am actually using logging - you're right I could just add a console handler. But I only want to do that if I'm in a terminal :-) Thanks!
Well, redirect with append—or even pipe to a log writer—is exactly what I was suggesting. It's not like writing >> or | is harder than writing >

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.