在此代码中,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]#
答案 0 :(得分:2)
在关闭stdout之前,.wait()
需要Popen
才能完成,否则会得到未定义的行为。
Popen("date", shell=True, stdout=file_).wait()
# ^ add this part!
我无法确定文件是如何在之后写入,但是我想这是您的操作系统的实现细节。