0

端末から結果を取得する必要があります

mask = "audio"
a = os.system("ls -l | grep %s | awk '{ print $9 }'" % mask)
print a # a = 0, that's the exit code

#=>
file1_audio
file2_audio
0

このコマンドは結果をコンソールに出力するだけですが、変数にキャプチャしたいのです。

4

1 に答える 1

4

subprocessモジュールを使用する

import subprocess

p = subprocess.Popen("ls -l | grep %s | awk '{ print $9 }'" % mask, 
    shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

shell=Trueパイプラインはシェルによって実行されるため、 が必要です。それ以外の場合 はNo such file or directory.

Python 2.7では、使用することもできます

output = subprocess.check_output(
    "ls -l | grep %s | awk '{ print $9 }'" % mask
    stderr=subprocess.STDOUT,
    shell=True)

subprocess.CalledProcessErrorしかし、パイプラインが 0 以外の終了コードを返した場合に a をスローするため、使用するのが面倒であり、stdout と stderr の両方をキャプチャするには、両方をインターリーブする必要があるため、多くの場合使用できません。

于 2013-08-17T01:40:39.257 に答える