20

次のような subprocess.popen() 関数を使用して、Python でコマンドを実行します。

omp_cmd = 'cat %s | omp -h %s -u %s -w %s -p %s -X -' %(temp_xml, self.host_IP, self.username, self.password, self.port)
xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)

シェルではエラーなしで正常に実行されますが、Python では次のようになります。

  File "/home/project/vrm/apps/audit/models.py", line 148, in sendOMP
    xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
  File "/usr/local/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/usr/local/lib/python2.7/subprocess.py", line 1228, in _execute_child
    raise child_exception
  OSError: [Errno 2] No such file or directory

エラーを検索しましたが、どれも問題を解決しませんでした。この問題の原因を知っている人はいますか? ありがとう。

4

2 に答える 2

25

コマンドを文字列として渡すPopen場合、およびコマンドに他のコマンドへのパイプがある場合は、shell=Trueキーワードを使用する必要があります。

私はompコマンドに特に精通していませんが、これは猫の無駄な使用のような匂いがします。これを達成するためのより良い方法は、次のようになると思います。

import shlex
omp_cmd = 'omp -h %s -u %s -w %s -p %s -X %s' %(self.host_IP, self.username, self.password, self.port, temp_xml)
xmlResult = Popen(shlex.split(omp_cmd), stdout=PIPE, stderr=STDOUT)

または、それが cat の無駄な使用でない場合 (実際には標準入力経由でファイルをパイプする必要があります)、サブプロセスでもそれを行うことができます:

import shlex
omp_cmd = 'omp -h %s -u %s -w %s -p %s -X -' %(self.host_IP, self.username, self.password)
with open(temp_xml) as stdin:
    xmlResult = Popen(shlex.split(omp_cmd), stdin=stdin, stdout=PIPE, stderr=STDOUT)
于 2012-07-19T18:21:07.467 に答える