2016-06-19 3 views
0


의 파일을 읽는 방법, 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]# 
+1

잘 우분투 나를 위해 작동 –

+0

옆으로 : 왜 당신은 루트 껍질에 있습니까? – edwinksl

+1

Popen이'stdout'을 닫기 전에 끝내기 위해서'wait()'를 고려 했습니까? –

답변

2

당신은 그렇지 않으면 당신은 정의되지 않은 동작을 얻을, 표준 출력을 닫기 전에 완료 될 때까지 Popen에 대한 .wait()해야합니다. 파일이 당신이 그것에서 읽으려고 후 에 기록하지만 난 상상 된 방법 내가 확실히 말할 수 없다

Popen("date", shell=True, stdout=file_).wait() 
#          ^add this part! 

은 당신의 OS에 대한 구현 세부입니다.