2011-09-28 5 views
7

Windows 및 Linux에서 모두 테스트 스위트를 실행하는 간단한 Python 스크립트가 있습니다. 모든 테스트는 출력을 개별 파일에 씁니다. 서브 프로세스를 사용합니다. 주기적으로 쉘 명령을 실행하려면 클래스를 엽니 다. 그런파이썬 하위 프로세스. 공개 및 비동기 출력

모든 쉘 명령 시작 : 그것은 잘 작동하지만 스크립트는 모든 출력 파일이 기록 된 전에 작업 을 완료

def system_execute(self, command, path, out_file): 
    params_list = command.split(' ') 
    file_path = os.path.join(path, out_file) 
    f = open(file_path, "w") 
    subprocess.Popen(params_list, stdout=f) 
    f.close() 

. 사실, 크기가 0 인 파일이 수백 개 있습니다. 출력을 작성하고 핸들을 닫는 데는 약간의 시간이 걸립니다. 누구나 왜 이상하게 작동하는지 이유를 설명 할 수 있습니까? 동일한 작업을 수행하는 동기식 방법이 있습니까?

감사 f.close() 전에

답변

15

, 당신은 우리의 서브 프로세스 wait()에 있습니다.

def system_execute(self, command, path, out_file): 
    params_list = command.split(' ') 
    file_path = os.path.join(path, out_file) 
    f = open(file_path, "w") 
    sp = subprocess.Popen(params_list, stdout=f) 
    sp.wait() 
    f.close() 

또는 쉽게 파일 처리를위한 단지

def system_execute(self, command, path, out_file): 
    params_list = command.split(' ') 
    file_path = os.path.join(path, out_file) 
    f = open(file_path, "w") 
    subprocess.call(params_list, stdout=f) 
    f.close() 

(또는,

[...] 
    with open(file_path, "w") as f: 
     subprocess.call(params_list, stdout=f) 
+0

덕분에, 그것은 작동 –

관련 문제