1

I am calling the executable from python script using sub process call. these are the following code I have used:

try:
    p = subprocess.Popen([abc.exe], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

except Exception as e:
    print str(e)

from abc.exe, I have return 1 in failure case and return 0 for success case. But I don't know how to check the return value in python script.

thanks,

4

3 回答 3

3

Popen.returncode包含进程终止时的返回码。您可以确保使用Popen.wait.

于 2013-09-16T13:24:34.323 回答
1

另一种方法是使用subprocess.check_output(),因为您提到了 Python 2.7。这将使用与 相同的参数运行命令Popen。命令的输出以字符串形式返回。如果命令返回非零值,subprocess.CalledProcessError则会引发异常。

所以我认为你可以将你的代码改写成这样:

try:
    output = subprocess.check_output(['abc.exe'], shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as ex:
    # an error occurred
    retcode = ex.returncode
    output = ex.output
else:
    # no error occurred
    process(output)

请注意,您不能使用stdoutin 参数,check_output因为它是在内部使用的。这是文档

于 2013-09-16T14:07:19.987 回答
1

您已保存为p的输出.communicate(),而不是Popen对象。也许尝试:

try:
    p = subprocess.Popen(['abc.exe'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

except OSError as e:
    print str(e)

stdoutdata, stderrdata = p.communicate()
retcode = p.returncode
于 2013-09-16T13:29:09.500 回答