Vaibhav Aggarwal
Vaibhav Aggarwal

Reputation: 1411

Python output to text file using cron-job

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!

Upvotes: 2

Views: 4390

Answers (2)

John
John

Reputation: 13699

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.

Upvotes: 2

go-oleg
go-oleg

Reputation: 19480

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

Upvotes: 3

Related Questions