简体   繁体   中英

How to check if I'm running in a shell (have a terminal) in Python?

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!

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())

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM