2017-11-20 3 views
0

ORIG라는 폴더의 디렉토리 구조를 얻기 위해 서브 프로세스 호출을 만들고 싶습니다.왜이 서브 프로세스 호출의 출력을 파이썬으로 읽을 수 없습니까?

import os 
from subprocess import call 
# copy the directory structure of ORIG into file 

f = open("outputFile.txt","r+b") 
call(['find', './ORIG', '-type', 'd'], stdout=f) 

a = f.read() 
print(a) 

내가 그것을 열 때 파일 outputFile.txt의 내용을 볼 같이 전화 명령이 작동 :

./ORIG 
./ORIG/child_one 
./ORIG/child_one/grandchild_one 
./ORIG/child_two 

왜 여기

내 코드입니다 이걸 읽거나 출력물을 출력 할 수 없습니까?

는 Luke.py의 제안에 따라, 나는 또한 다음을 시도 :

import os 
import re 
from subprocess import call, PIPE 

# copy the directory structure of ORIG into file 
# make directory structure from ORIG file in FINAL folder 

process = call(['find', './ORIG', '-type', 'd'], stdout=PIPE, stderr=PIPE) 
stdout, stderr = process.communicate() 

if stderr: 
    print stderr 
else: 
    print stdout 

이 나에게 outut 제공 :

Traceback (most recent call last): 
    File "feeder.py", line 9, in <module> 
    stdout, stderr = process.communicate() 
AttributeError: 'int' object has no attribute 'communicate' 

답변

0

이 Popen-

시도를 가져해야합니다

하위 프로세스의 PIPE.

process = subprocess.Popen(['find', './ORIG', '-type', 'd'], stdout=PIPE, stderr=PIPE) 
stdout, stderr = process.communicate() 

if stderr: 
    print stderr 
else: 
    print stdout 
+0

나는 당신의 제안을 시도했고 그것은 나에게 오류를 주었다. 나는 나의 질문을 업데이트했다. –

+0

subprocess.Popen 대신 사용하려고합니다 - 편집 된 답변 –

+0

그 트릭을 했어, 고마워. 파이썬이 원래 코드로 성공적으로 작성한 txt 파일을 읽을 수없는 이유를 설명 할 수 있다면 도움이 될 것입니다. –

2

첫 번째 : 외부 프로그램을 호출 할 필요가 없습니다. 어떤 경로의 서브 디렉토리를 얻고 싶다면 파이썬 함수 os.walk이있다. 이를 사용하고 각 항목을 os.path.isdir 또는 예 : os.fwalk을 사용하고 디렉토리를 사용하십시오.

외부 프로그램을 호출하여 표준 출력을 얻으려면 일반적으로 상위 레벨 함수 subprocess.run이 적합합니다. 당신이 표준 출력을 얻을 수 있습니다 : 임시 파일 또는 낮은 수준의 기능에 대한 요구없이

subprocess.run(command, stdout=subprocess.PIPE).stdout 

.

+0

좋은 물건 - 사용자가 구체적으로 묻는 것처럼 하위 프로세스 만 사용했습니다. –

0

쓰기 및 읽기 사이에 파일을 닫았다가 다시 열지 않으려면 seek 명령을 사용하여 처음부터 파일을 읽을 수 있습니다.

import os 
from subprocess import call 
# copy the directory structure of ORIG into file 

f = open("outputFile.txt","r+b") 
call(['find', './ORIG', '-type', 'd'], stdout=f) 

# move back to the beginning of the file 
f.seek(0, 0) 

a = f.read() 
print(a)