简体   繁体   中英

How can I tell if my script is being run from a cronjob or from the command line?

I have a script and it's display show's upload progress by writing to the same console line. When the script is run from a cron job, rather than writing to a single line, I get many lines:

***   E0710091001.DAT  ***   [0.67%]
***   E0710091001.DAT  ***   [1.33%]
***   E0710091001.DAT  ***   [2.00%]
***   E0710091001.DAT  ***   [2.66%]
***   E0710091001.DAT  ***   [3.33%]
***   E0710091001.DAT  ***   [3.99%]
***   E0710091001.DAT  ***   [4.66%]
***   E0710091001.DAT  ***   [5.32%]
***   E0710091001.DAT  ***   [5.99%]
***   E0710091001.DAT  ***   [6.65%]
***   E0710091001.DAT  ***   [7.32%]
***   E0710091001.DAT  ***   [7.98%]
***   E0710091001.DAT  ***   [8.65%]
***   E0710091001.DAT  ***   [9.32%]
***   E0710091001.DAT  ***   [9.98%]
***   E0710091001.DAT  ***   [10.65%]
***   E0710091001.DAT  ***   [11.31%]
***   E0710091001.DAT  ***   [11.98%]
***   E0710091001.DAT  ***   [12.64%]
***   E0710091001.DAT  ***   [13.31%]
***   E0710091001.DAT  ***   [13.97%]
***   E0710091001.DAT  ***   [14.64%]
***   E0710091001.DAT  ***   [15.30%]
***   E0710091001.DAT  ***   [15.97%]
***   E0710091001.DAT  ***   [16.63%]
***   E0710091001.DAT  ***   [17.30%]
***   E0710091001.DAT  ***   [17.97%]
***   E0710091001.DAT  ***   [18.63%]

I just want to know if I can tell from inside the script if it's being called from cron, and if so, I won't display this output.

you could create a flag. Possibly undocumented that your cron job would pass to the utility to structure the output.

我将检查sys.stderr.isatty() -这样一来,无论何时用户无法立即感知到stderr,都可以避免无用的“装饰”输出。

See code below. Replace my print statements with what you want to show.

import sys
if sys.stdout.isatty():
    print "Running from command line"
else:
    print "Running from cron"

You want to check if you're on a terminal or not. See this stack overflow question: How to detect if my shell script is running through a pipe?

一种简单的方法是让脚本采用一个参数,该参数表示抑制该输出,并在您从cron调用它时提供该参数。

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