将 os.system 的输出分配给变量并防止其显示在屏幕上[重复]
- 2024-12-13 08:36:00
- admin 原创
- 138
问题描述:
我想将我运行的命令的输出分配os.system
给一个变量,并阻止它输出到屏幕上。但是,在下面的代码中,输出被发送到屏幕,打印的值为var
0,我猜这表示命令是否成功运行。有没有办法将命令输出分配给变量并阻止它显示在屏幕上?
var = os.system("cat /etc/services")
print var #Prints 0
解决方案 1:
从我很久以前问过的这个问题popen
来看,你可能想要使用的是:
os.popen('cat /etc/services').read()
来自Python 3.6 的文档,
这是使用 subprocess.Popen 实现的;请参阅该类的文档以了解管理和与子进程通信的更强大的方法。
以下是相应的代码subprocess
:
import subprocess
proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print("program output:", out)
解决方案 2:
您可能还想查看subprocess
模块,它是为了替换整个 Pythonpopen
类型调用系列而构建的。
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)
它的优势在于,在调用命令的方式、标准输入/输出/错误流的连接位置等方面具有很大的灵活性。
解决方案 3:
命令模块是一种相当高级的方式来实现这一点:
import commands
status, output = commands.getstatusoutput("cat /etc/services")
状态为0,输出是/etc/services的内容。
解决方案 4:
对于 Python 3.5+,建议使用subprocess 模块中的 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"])
解决方案 5:
我知道这个问题已经被回答过了,但是我想分享一种通过使用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')
解决方案 6:
我使用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
解决方案 7:
Python 2.6 和 3 明确指出避免对 stdout 和 stderr 使用 PIPE。
正确的方法是
import subprocess
# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()
# now operate on the file
解决方案 8:
from os import system, remove
from uuid import uuid4
def bash_(shell_command: str) -> tuple:
"""
:param shell_command: your shell command
:return: ( 1 | 0, stdout)
"""
logfile: str = '/tmp/%s' % uuid4().hex
err: int = system('%s &> %s' % (shell_command, logfile))
out: str = open(logfile, 'r').read()
remove(logfile)
return err, out
# Example:
print(bash_('cat /usr/bin/vi | wc -l'))
>>> (0, '3296
')```
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD