13,489 views
この記事は最終更新から 2373日 が経過しています。
(37) subprocessで外部のプログラムを実行では、subprocessモジュールを使って外部プログラムを実行する方法を記した。しかし、この方法だと 複数コマンドをパイプで繋いだ場合にうまく動かない のであった…
つまり、これは OK
cmd1 = "ls -lt"
sp.call(cmd1.split(" "))
これは NOK
cmd1 = "ls -lt | grep txt"
sp.call(cmd1.split(" "))
ではどうするか?
cmd1 = "ls -lt" cmd2 = "grep txt" res = sp.Popen(cmd1.split(" "), stdout=sp.PIPE) sp.check_output(cmd2.split(" "), stdin=res.stdout)
または、
cmd = "ls -lt | grep txt" res = sp.Popen(cmd, shell=True, stdout=sp.PIPE) stdout,strerr = res.communicate() print stdout
cmd = "ls -lt | grep txt" res = sp.Popen(cmd, shell=True, stdout=sp.PIPE) res.communicate()[0]
しかし、shell=True は 任意のコマンドを自由自在に操られてしまう危険性 がある。
しっかりとサニタイズされていない外部入力データを使うならば shell=True を使ってはダメ!
アクセス数(直近7日): ※試験運用中、BOT除外簡易実装済2026-04-19: 0回 2026-04-18: 0回 2026-04-17: 0回 2026-04-16: 0回 2026-04-15: 0回 2026-04-14: 0回 2026-04-13: 0回