2017-11-20 13 views
0

サブプロセスコールを作成して、ORIGというフォルダのディレクトリ構造を取得したいとします。ここでなぜこのサブプロセス呼び出しの出力をPythonで読むことができませんか?

は私のコードです:私はそれを開いたとき、私はから、OutputFile.txtファイルの内容を見ると

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) 

コールコマンドは、働いている:

./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

それはトリック、ありがとうでした。なぜPythonが元のコードで正常に書いたtxtファイルを読むことができないのか説明できるなら、それも役に立ちます。 –

2

最初に:外部プログラムを呼び出す必要はありません。あるパスのサブディレクトリを取得したい場合は、Python関数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) 
関連する問題