2

I have a python script i want to run every 5 minutes to check for a new file on a server. I know i can do that with cron-job. But in the directory of my python script i have a folder called 'logs'. Is there a way that i can output whatever my python script returned(it returns at least 20-30 lines every time) to a text file for the every 5 minutes into the logs folder. i want to be able to just search through the files to see the output for each run. So according to my calculations, i should get about 288 log files per day.

Also another doubt that i had is that the script shows some live stuff(like a download progress bar), so would there be a problem with that?

Thanks!

jww
  • 97,681
  • 90
  • 411
  • 885
Vaibhav Aggarwal
  • 1,381
  • 2
  • 19
  • 30

2 Answers2

3

If you don't want to modify the script itself, you can redirect the output to a timestamped file:

./your/script.py > "your-log-file-"`date +"%Y-%m-%d-%H-%M-%S"`".log"

Which would output files of the format:

your-log-file-2013-07-01-20-22-45.log

go-oleg
  • 19,272
  • 3
  • 43
  • 44
  • will i be able to use this with cron-job? i know you can put the '>' to specify the location of the log, but can i use those wildcards you used in the txt doc? Thanks – Vaibhav Aggarwal Jul 02 '13 at 03:38
  • > and >> (the latter being append) are the standard ways of redirecting the stdout of a command to a file. Crontab simply spawns a new shell and executes the command specified, so if that command redirects stdout or stderr it'll be executed as if it was a regular shell. [Example here.](http://stackoverflow.com/a/24957849/2568279) – Agustín Lado Apr 20 '16 at 14:56
2

If you want your standart output to go to a file you can do that like this.

import sys
sys.stdout = open('file.txt', 'w')

that way when your python script prints out stuff it will go to file.txt instead of stdout.

Here is a copy paste example.

import sys
sys.stdout = open("file.txt", 'w')

for n in xrange(100):
    print n

#I bet you can guess what you're going to see in file.txt

this will print 0-99 in a text file called file.txt and nothing will show up on your console.

Community
  • 1
  • 1
John
  • 13,197
  • 7
  • 51
  • 101