在Python中执行externall编译的程序

时间:2017-02-23 19:57:54

标签: python shell subprocess

我想用Python执行外部编译程序。在shell中,

./bin/myProgram ./dir1/arg1 ./dir/arg2 arg3 arg3 arg4

我的Python脚本如下:

import subprocess
subprocess.call(["./Users/Solar/Desktop/parent/child1/child2/bin/myProgram",
                 "/Users/Solar/Desktop/parent/child1/child2/dir1/arg1",
                 "/Users/Solar/Desktop/parent/child1/child2/dir1/arg2",
                 "arg3", "arg4", "arg5"])

但是我收到了这个错误:

Traceback (most recent call last):
  File "/Users/Solar/Desktop/test.py", line 5, in <module>
    "32", "0.06", "15"])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Process finished with exit code 1
你可以帮帮我吗?提前谢谢!!

2 个答案:

答案 0 :(得分:0)

subprocess.Popen发布时

OSError: [Errno 2] No such file or directory

这只是因为找不到可执行文件(如果找不到其中一个文件参数,那么它就是报告错误的子进程,并且不会抛出异常)

在您的情况下,考虑到./Users/...有效(根据当前目录),/Users/可能无效,这就是您的问题。

"./Users/Solar/Desktop/parent/child1/child2/bin/myProgram"应为"/Users/Solar/Desktop/parent/child1/child2/bin/myProgram"

注意:更好的编码可以避免错误:

import subprocess
root = "/Users/Solar/Desktop/parent/child1/child2"
subprocess.call([os.path.join(root,"bin/myProgram"),
                 os.path.join(root,"dir1/arg1"),
                 os.path.join(root,"dir1/arg2"),
                 "arg3", "arg4", "arg5"])

答案 1 :(得分:0)

它已经解决了,我只需要执行

Month month = Month.valueOf("January".toUpperCase());
System.out.println(month.getValue() + " : " + month);
// 1 : JANUARY

而不是

subprocess.call(["/Users/Solar/Desktop/parent/child1/child2/bin/myProgram",
                 "/Users/Solar/Desktop/parent/child1/child2/dir1/arg1",

...

谢谢大家!!