端末から結果を取得する必要があります
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
このコマンドは結果をコンソールに出力するだけですが、変数にキャプチャしたいのです。
端末から結果を取得する必要があります
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
このコマンドは結果をコンソールに出力するだけですが、変数にキャプチャしたいのです。
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 の両方をキャプチャするには、両方をインターリーブする必要があるため、多くの場合使用できません。