简体   繁体   English

如何使用子进程获取输出和返回代码?

[英]How to get both the output and return code with subprocess?

I'm using the subprocess module to execute my C program, and at the end I want to get both the return code and the output returned from the program.我正在使用subprocess模块来执行我的 C 程序,最后我想获得程序返回的返回码和输出。 I tried this:我试过这个:

result = subprocess.check_output(['src/main', '-n {0}'.format(n)], universal_newlines=True)

The above captures the output of the program, it will only raise an error if the return code is non-zero.以上捕获了程序的输出,如果返回码非零,它只会引发错误。 The point is that I do not want to raise an error on non-zero error code, instead I want to use it in an if statement, and if the return code is non-zero I want to re-run the process.关键是我不想在非零错误代码上引发错误,而是想在if语句中使用它,如果返回代码非零,我想重新运行该过程。

Now, if I change it to run , and call as:现在,如果我将其更改为run ,并调用为:

result = subprocess.run(['src/main', '-n {0}'.format(n)])

Then, I can do result.returncode to get the return code, but when I do result.stdout , it prints None .然后,我可以执行result.returncode来获取返回码,但是当我执行result.stdout ,它会打印None Is there a way to get both the return code and the actual output?有没有办法同时获得返回码和实际输出?

In order to capture output with subprocess.run() , you need to pass stdout=subprocess.PIPE .为了使用subprocess.run()捕获输出,您需要传递stdout=subprocess.PIPE If you want to capture stderr as well, also pass stderr=subprocess.PIPE (or stderr=subprocess.STDOUT to cause stderr to be merged with stdout in the result.stdout attribute).如果您还想捕获 stderr,还可以通过stderr=subprocess.PIPE (或stderr=subprocess.STDOUT使 stderr 与result.stdout属性中的 stdout 合并)。 For example:例如:

result = subprocess.run(['src/main', '-n {0}'.format(n)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Or, if you are using Python 3.7 or higher:或者,如果您使用的是 Python 3.7 或更高版本:

result = subprocess.run(['src/main', '-n {0}'.format(n)], capture_output=True)

You may also want to set universal_newlines=True to get stdout as a string instead of bytes.您可能还想设置universal_newlines=True以将stdout 作为字符串而不是字节获取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM