简体   繁体   中英

Redirect python output to file

I have the following code in bash script

python -u - << EOF
from my.package import script
script.run()
EOF
>> /path/to/log/file

In script.py there are a number of print statements and I would like to redirect that output from the console to a file. The file gets created successfully, but it's empty.

How can I go about this? What am I missing here?

The idea is right, but the way you re-direct the output to a file from here-document is wrong, Heredocs themselves re-directs just like any other commands, just do

python -u - << EOF >> /path/to/log/file
from my.package import script
script.run()
EOF

try this,

import sys
f = open("log_file.txt", 'w')
sys.stdout = f
print "My print statements"
f.close()

Right syntax is:

python -u - >> /path/to/log/file << EOF
from my.package import script
script.run()
EOF

The reason is that if you write in bash something like that:

util_1 | util_2 | util_3 >> some_file < another_file

or

util_1 | util_2 | util_3 >> some_file << EOF
...
EOF

another_file or here-document goes to the standard input of the first utility in pipeline (in this case to util_1 ).

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