简体   繁体   English

python&php-stdout重定向无法正常工作

[英]python & php - stdout redirect not working properly

In my python script I redirect stdout to a file: 在我的python脚本中,我将stdout重定向到一个文件:

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. 这可以正常工作,但是当我从PHP启动python脚本时,文件已正确创建,但没有添加任何行。 The log.txt simply stays empty! log.txt只是保持为空!

<?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. 有趣的是,在Windows PC上,情况正好相反。 Python does not print the test line but when called from PHP it does! Python不会打印测试行,但是当从PHP调用时会打印! Possibly it is our OS environments or versions as I use Python 3 and PHP 5.4. 当我使用Python 3和PHP 5.4时,可能是我们的操作系统环境或版本。 However, in both runs of .py script below works in setting the stdout back to original state. 但是,在以下两种.py脚本运行中,都可以将stdout设置回原始状态。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM