[英]How to read file of subprocess output
在此代码中,subprocess.Popen使用date
输出创建/tmp/test.txt。 为什么第二个“打印线”不起作用? 多谢您的协助。
test]# touch /tmp/test.txt
test]# ./x1.py
/tmp/test.txt
()
/tmp/test.txt
()
test]# ./x1.py
/tmp/test.txt
('Sun Jun 19 15:10:21 PDT 2016\n',)
/tmp/test.txt
()
test]# cat x1.py
#!/usr/bin/python
from subprocess import Popen, PIPE
filename = "/tmp/test.txt"
lines = tuple(open(filename, 'r'))
print filename
print lines # this is not empty
file_ = open(filename, "w")
Popen("date", shell=True, stdout=file_)
file_.close()
lines = tuple(open(filename, 'r'))
print filename
# why is this empty even if file_ definitely created the /tmp/test.txt ?
print lines
test]#
你需要.wait()
为Popen
在关闭标准输出前完成,否则,你得到了一个未定义的行为。
Popen("date", shell=True, stdout=file_).wait()
# ^ add this part!
在您尝试从中读取文件后,我无法确定该文件是如何写入的,但我想那是您的OS的实现细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.