Adrian Daniel Culea
Adrian Daniel Culea

Reputation: 181

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?

Upvotes: 1

Views: 442

Answers (3)

cltif
cltif

Reputation: 51

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).

Upvotes: 0

Inian
Inian

Reputation: 85530

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

Upvotes: 2

Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20137

try this,

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

Upvotes: 0

Related Questions