简体   繁体   中英

Stdout not being written to file?

I'm having trouble with something here, and I don't know whats going on.

I have a python script test.py that connects to my server, gets some information, then prints this information (in an infinite loop, essentially).

I also have a bash script starter.sh as follows:

#!/bin/bash

if [ ! `pgrep python` ]; then
    cd /home/user/test
    python test.py
fi

When I run it from the terminal, everything is fine and works as expected. It simply writes some text to the console.

The problem happens when I involve cron jobs.

I have the following cron job:

*/1 * * * * /home/user/test/starter.sh >> /home/user/test/log.txt 2>&1

When cron job runs (and I know it runs because I check my server and it receives a connection, a request for data, and then sends the data.

I want to log whatever my python script prints though. But nothing is being written to the log?? What do I do

EDIT: Simply running python test.py>>echo.txt or python test.py>echo.txt doesnt seem to work either.

I'm using pythons print function to print data

Ok, I seem to figured out the issue (if anyone else happens to have this same problem). The problem is print in python 2.7 doesn't flush stdout. by running python -u test.py this solves the problem and works fine

from man, here is what the -u switch does:

-u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xread- lines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop

I'm also a starter @ bash scripting.It should work i guess

#!/bin/bash

if [ ! `pgrep python` ]; then
    cd /home/user/test
    python test.py >> /home/user/test/log.txt
fi

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