我试图从Python内部运行一些外部可执行代码,然后利用输出。我使用的代码需要一个外部文件并返回一个单一数字(编码的图像数量该文件)。当我在命令行中运行,我看到以下内容:与Python子进程混淆
[email protected]:~/nist/hsfsys/bin$ ./nummis /usr/local/hsfsys/data/by_class/4a/train_4a.mis
3962
其中3962是一个正确的输出尽可能接近我可以告诉
然而,当我尝试使用子从内Python中,我得到出现以下错误:
[email protected]:~/nist/hsfsys/bin$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.check_output(["./nummis","/usr/local/hsfsys/data/by_class/4a/train_4a.mis"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 544, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['./nummis', '/usr/local/hsfsys/data/by_class/4a/train_4a.mis']' returned non-zero exit status 32
>>> subprocess.call(["./nummis","/usr/local/hsfsys/data/by_class/4a/train_4a.mis"])
3962
32
我该如何解释此“非零退出状态32”?如果有什么不对,我为什么不在命令行上看到它?如果没有错,为什么Python抱怨&我怎么才能让它停止抱怨?
您看到的行为与子进程.check_call()函数相同。我猜你有两个主要选择:将你的调用包装在异常处理程序中,或者使用subprocess.Popen并提供你自己的处理(check_output()是一些.Popen()代码的包装)。 另一个相当复杂的方法是调用['/ bin/sh','-c','your_command your_args;退出0']强制子进程返回零,不管你的命令返回什么。但那真是太傻了。 (你也可以重新编写“nummis”命令来返回EXIT_SUCCESS) –
@Jim Dennis谢谢。使用p = subprocess.Popen(.....,stdout = subprocess.PIPE),然后是z = p.communicate(),可以访问我想要的输出。 – user1245262