2

コマンドから出力を取得し、それをファイルまたは変数に入れることができるpythonスクリプトを作成しようとしています(変数が好ましい)。

私のコードでは、出力をStringIO()オブジェクトにリダイレクトしました。StringIO()それから、出力をコマンドにして、そのオブジェクトに入れたいと思います。

これが私のコードのサンプルです:

from StringIO import StringIO
import sys

old_stdout = sys.stdout

result = StringIO()
sys.stdout = result

# This will output to the screen, and not to the variable
# I want this to output to the 'result' variable
os.system('ls -l')

また、結果を取得して文字列に入れるにはどうすればよいですか?

前もって感謝します!!

4

1 に答える 1

5
import subprocess
sp = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
output, _ = sp.communicate()
print "Status:", sp.wait()
print "Output:"
print output
于 2012-11-20T15:35:07.247 に答える