How do I know if my script is running from cronjob or from the command line?

I have a script, and it displays the progress of loading the download, writing to the same console line. When a script is run from a cron job and not written 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 is being called from cron, and if so, I will not display this output.

+3
source share
5 answers

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"
+6
source

you can create a flag. It may be undocumented that your cron job goes to a utility for structuring output.

+10
source

sys.stderr.isatty() - , "" stderr, .

+9
source

You want to check whether you are on the terminal or not. See This question: How to determine if my shell script works through a pipe?

+6
source

An easy way would be to have a script accept an argument that means suppressing this output, and provide that argument when you call it from cron.

+2
source

Source: https://habr.com/ru/post/1712304/


All Articles