在Python中 - 如何执行没有输出的系统命令

时间:2022-07-24 18:17:01

Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value.

Python中是否有内置方法来执行系统命令而不显示输出?我只想获取返回值。

It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the redirection myself, but I'm hoping for a built-in solution.

重要的是它是跨平台的,因此将输出重定向到/ dev / null将无法在Windows上运行,反之亦然。我知道我可以检查os.platform并自己构建重定向,但我希望有一个内置的解决方案。

2 个解决方案

#1


import os
import subprocess
subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)

#2


You can redirect output into temp file and delete it afterward. But there's also a method called popen that redirects output directly to your program so it won't go on screen.

您可以将输出重定向到临时文件,然后将其删除。但是还有一种名为popen的方法可以将输出直接重定向到您的程序,因此它不会出现在屏幕上。

#1


import os
import subprocess
subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)

#2


You can redirect output into temp file and delete it afterward. But there's also a method called popen that redirects output directly to your program so it won't go on screen.

您可以将输出重定向到临时文件,然后将其删除。但是还有一种名为popen的方法可以将输出直接重定向到您的程序,因此它不会出现在屏幕上。