2024-03-28 19:40:50 发布
网友
我想将使用os.system运行的命令的输出分配给一个变量,并防止它被输出到屏幕。但是,在下面的代码中,输出被发送到屏幕,并且为var打印的值为0,我猜这表示命令是否成功运行。是否有任何方法可以将命令输出分配给变量并阻止其显示在屏幕上?
os.system
var
var = os.system("cat /etc/services") print var #Prints 0
命令模块是一种相当高级的方法:
import commands status, output = commands.getstatusoutput("cat /etc/services")
状态为0,输出为/etc/services的内容。
从我很久以前问过的“Equivalent of Bash Backticks in Python”中,您可能想要使用的是popen:
popen
os.popen('cat /etc/services').read()
从docs for Python 3.6
This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.
以下是subprocess的对应代码:
subprocess
import subprocess proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print "program output:", out
您可能还想看看subprocess模块,它是为替换整个Python popen类型调用家族而构建的。
import subprocess output = subprocess.check_output("cat /etc/services", shell=True)
它的优点是,在调用命令、连接标准输入/输出/错误流等方面有很大的灵活性
命令模块是一种相当高级的方法:
状态为0,输出为/etc/services的内容。
从我很久以前问过的“Equivalent of Bash Backticks in Python”中,您可能想要使用的是
popen
:从docs for Python 3.6
以下是
subprocess
的对应代码:您可能还想看看
subprocess
模块,它是为替换整个Pythonpopen
类型调用家族而构建的。它的优点是,在调用命令、连接标准输入/输出/错误流等方面有很大的灵活性
相关问题 更多 >
编程相关推荐