bash 如何避免 os.system() 在 python 中打印出返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8823117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to avoid os.system() printing out return value in python
提问by Shang Wang
I'm using Python to call bash to execute another bash script:
我正在使用 Python 调用 bash 来执行另一个 bash 脚本:
begin = int(sys.argv[1])
result = os.system("/tesladata/isetools/cdISE.bash %s" %begin)
After I printed result, it not only gives me the output but also the return status (0here).
What should I do if I only need the output?
And also, just for curiosity, how many ways are there to call bash in Python? I'll be glad if somebody can give me some references of how to use them, I've found only os.system()and os.popen()so far.
在我打印之后result,它不仅给了我输出,还给了我返回状态(0这里)。如果只需要输出怎么办?
而且,出于好奇,在 Python 中有多少种调用 bash 的方法?我会很高兴,如果有人可以给我如何使用它们的一些参考,我只发现os.system()和os.popen()至今。
回答by AdamKG
Actually, resultis only the return status as an integer. The thing you're calling writes to stdout, which it inherits from your program, so you're seeing it printed out immediately. It's never available to your program.
实际上,result只是返回状态为整数。你调用的东西写入标准输出,它从你的程序继承,所以你会看到它立即打印出来。它永远无法用于您的程序。
Check out the subprocess module docs for more info:
查看子流程模块文档以获取更多信息:
http://docs.python.org/library/subprocess.html
http://docs.python.org/library/subprocess.html
Including capturing output, and invoking shells in different ways.
包括捕获输出,以及以不同方式调用 shell。
回答by Michael Mior
You can just throw away any output by piping to /dev/null.
您可以通过管道丢弃任何输出/dev/null。
begin = int(sys.argv[1])
result = os.system("/tesladata/isetools/cdISE.bash %s > /dev/null" %begin)
If you don't want to display errors either, change the >to 2&>to discard stderras well.
如果您也不想显示错误,请将>to也更改2&>为丢弃stderr。
回答by William Pursell
Your python script does not have the output of the bash script at all, but only the "0" returned by it. The output of the bash script went to the same output stream as the python script, and printed before you printed the value of result. If you don't want to see the 0, do not print result.
您的 python 脚本根本没有 bash 脚本的输出,而只有它返回的“0”。bash 脚本的输出与 python 脚本进入相同的输出流,并在打印结果值之前打印。如果您不想看到 0,请不要打印结果。

