Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

popen - python: raise child_exception, OSError: [Errno 2] No such file or directory

I execute a command in python using subprocess.popen() function like the following:

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)

In the shell it runs fine without error, but in python I get:

  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

I searched the error but none of them solved my problem. Does anyone know what's the cause of this issue? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're going to pass the command as a string to Popen and if the commands have pipes to other commands in there, you need to use the shell=True keyword.

I'm not particularly familiar with the omp command, but this smells an awful lot like a useless use of cat. I would think that a better way to achieve this would be to:

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)

Or, if it's not a useless use of cat (You really do need to pipe the file in via stdin), you can do that with subprocess too:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...