bash Python:os.system() 没有返回或错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8592762/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:12:16  来源:igfitidea点击:

Python: os.system() without return or error

pythonbasherror-handlingsystemsubprocess

提问by tkbx

I need to use os.system() a few times in my script, but I don't want errors from the shell to appear in my script's window. Is there a way to do this? I guess it's sort of like silent commands, running to their full extent, but not returning anytext. I can't use 'try', because it's not a Python error.

我需要在我的脚本中多次使用 os.system(),但我不希望 shell 中的错误出现在我的脚本窗口中。有没有办法做到这一点?我想这有点像无声命令,运行到它们的全部范围,但不返回任何文本。我不能使用 'try',因为它不是 Python 错误。

回答by NPE

You could redirect the command's standard error away from the terminal. For example:

您可以将命令的标准错误重定向到远离终端。例如:

# without redirect
In [2]: os.system('ls xyz')
ls: cannot access xyz: No such file or directory
Out[2]: 512

# with redirect
In [3]: os.system('ls xyz 2> /dev/null')
Out[3]: 512

P.S. As pointed out by @Spencer Rathbun, the subprocessmodule should be preferred over os.system(). Among other things, it gives you direct control over the subprocess's stdout and stderr.

PS 正如@Spencer Rathbun 所指出的,该subprocess模块应该优于os.system(). 除此之外,它使您可以直接控制子进程的 stdout 和 stderr。

回答by Eric O Lebigot

The recommended wayto call a subprocess and manipulate its standard output and standard error is to use the subprocessmodule. Here is how you can suppress both the standard output and the standard output:

调用子进程并操作其标准输出和标准错误的推荐方法是使用子进程模块。以下是抑制标准输出和标准输出的方法:

import subprocess

# New process, connected to the Python interpreter through pipes:
prog = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
prog.communicate()  # Returns (stdoutdata, stderrdata): stdout and stderr are ignored, here
if prog.returncode:
    raise Exception('program returned error code {0}'.format(prog.returncode))

If you want the subprocess to print to standard output, you can simply remove the stdout=….

如果您希望子进程打印到标准输出,您可以简单地删除stdout=….