将 os.system 的输出分配给变量并防止其显示在屏幕上 [英] Assign output of os.system to a variable and prevent it from being displayed on the screen

查看:45
本文介绍了将 os.system 的输出分配给变量并防止其显示在屏幕上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我使用 os.system 运行的命令的输出分配给一个变量,并防止它输出到屏幕上.但是,在下面的代码中,输出被发送到屏幕并且 var 打印的值是 0,我猜这表示命令是否成功运行.有什么方法可以将命令输出分配给变量并阻止它在屏幕上显示?

I want to assign the output of a command I run using os.system to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for var is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign the command output to the variable and also stop it from being displayed on the screen?

var = os.system("cat /etc/services")
print var #Prints 0

推荐答案

来自 "相当于 BashPython 中的反引号",我很久以前就问过,您可能想要使用的是 popen:

From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read()

来自 Python 3.6 文档

这是使用 subprocess.Popen 实现的;看那个班的有关更强大的管理和沟通方式的文档子流程.

This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.

<小时>

下面是subprocess对应的代码:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out

这篇关于将 os.system 的输出分配给变量并防止其显示在屏幕上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆