我想将我运行的命令的输出分配给os.system
变量,并防止它输出到屏幕.但是,在下面的代码中,输出被发送到屏幕并且打印的var
值为0,我猜这表示命令是否成功运行.有没有办法将命令输出分配给变量并阻止它显示在屏幕上?
var = os.system("cat /etc/services")
print var #Prints 0
Run Code Online (Sandbox Code Playgroud)
Chr*_*nch 378
从我很久以前问过的" Python中的Bash Backticks的等价 ",您可能想要使用的是popen
:
os.popen('cat /etc/services').read()
Run Code Online (Sandbox Code Playgroud)
这是使用subprocess.Popen实现的; 查看该类的文档,了解更有效的方法来管理子进程并与子进程通信.
这是相应的代码subprocess
:
import subprocess
proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
Run Code Online (Sandbox Code Playgroud)
Wal*_*ndt 166
您可能还想查看该subprocess
模块,该模块是为了替换整个Python popen
类型的调用而构建的.
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)
Run Code Online (Sandbox Code Playgroud)
它的优点是调用命令的方式有很大的灵活性,标准的输入/输出/错误流是连接的,等等.
ian*_*ury 45
命令模块是一种相当高级的方法:
import commands
status, output = commands.getstatusoutput("cat /etc/services")
Run Code Online (Sandbox Code Playgroud)
status为0,输出是/ etc/services的内容.
Vas*_*kis 23
我知道这已经得到了解答,但我想通过使用from x import x
和函数分享一种更好看的方式来调用Popen :
from subprocess import PIPE, Popen
def cmdline(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return process.communicate()[0]
print cmdline("cat /etc/services")
print cmdline('ls')
print cmdline('rpm -qa | grep "php"')
print cmdline('nslookup google.com')
Run Code Online (Sandbox Code Playgroud)
Chi*_*nke 19
对于python 3.5+,建议您使用子进程模块中的run函数.这将返回一个CompletedProcess
对象,您可以从中轻松获取输出以及返回代码.由于您只对输出感兴趣,因此可以编写这样的实用程序包装器.
from subprocess import PIPE, run
def out(command):
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
return result.stdout
my_output = out("echo hello world")
# Or
my_output = out(["echo", "hello world"])
Run Code Online (Sandbox Code Playgroud)
我用 os.system 临时文件来做:
import tempfile,os
def readcmd(cmd):
ftmp = tempfile.NamedTemporaryFile(suffix='.out', prefix='tmp', delete=False)
fpath = ftmp.name
if os.name=="nt":
fpath = fpath.replace("/","\\") # forwin
ftmp.close()
os.system(cmd + " > " + fpath)
data = ""
with open(fpath, 'r') as file:
data = file.read()
file.close()
os.remove(fpath)
return data
Run Code Online (Sandbox Code Playgroud)