简体   繁体   中英

python & php - stdout redirect not working properly

In my python script I redirect stdout to a file:

sys.stdout = open("/home/pi/log.txt", "w")
print "test"

This works fine, but when I start the python script from a PHP the file is created correctly, but no lines are added to it. The log.txt simply stays empty!

<?php
exec('sudo -u pi python /home/pi/partyknipse/admin/upload.py')
?>

Would appreciate any suggestion.

Interestingly, on my Windows PC, I get the reverse. Python does not print the test line but when called from PHP it does! Possibly it is our OS environments or versions as I use Python 3 and PHP 5.4. However, in both runs of .py script below works in setting the stdout back to original state. Consider it on your end:

saveout = sys.stdout                      # SAVE TO RETURN BACK
sys.stdout = open("log.txt", "w")
print("test")
sys.stdout = saveout                      # RESET TO NORMAL STATE

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