如何在Python中存储os.system打印到stdout的返回值?

7

我正在编写一个Python脚本,用于检查特定IP/端口的活动连接数。为此,我使用os.system('my_command')来获取输出。os.system返回我传递给它的命令的退出状态(0表示命令无错误返回)。 如何将os.system抛出到STDOUT的值存储在变量中?以便稍后在函数中可以使用该变量进行计数。 类似subprocess、os.popen等模块可以帮助。有人能提供建议吗?

4个回答

18
a=os.popen("your command").read()

新的结果存储在变量a中 :)


正确的那个对我没用,但这个完美无缺! - VicoMan

6
import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = p.communicate()

1
不需要在Python中使用括号。元组可以隐式创建并自动打包和解包。是的,然后您可以执行print 'The output was', out, 'and the error was', error - agf
好的,明白了。这是执行以下netstat命令的正确语法吗 -> result = subprocess.Popen(["netstat -plant | awk '{print $4}' | grep %s:%s | wc -l' %(ip,port)"], stdout=subprocess.PIPE, stderr= subprocess.PIPE) ?我得到一个错误:File "/usr/lib/python2.7/subprocess.py", line 672, in init errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1202, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory 为什么会出现这种情况呢? - Ashutosh Narayan
请编辑并用反引号 ``` 包围代码,以便阅读。 - agf
尝试使用以下代码:result = subprocess.Popen('''sh -c "netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"''') 编辑:或者像@Jakob-Bowyer在下面建议的那样,尝试使用 shell=True。这是必需的,因为您不仅要运行一个命令,而是要使用 shell 的管道 | 功能。 - agf
result = subprocess.Popen(["netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"], stdout=subprocess.PIPE, stderr= subprocess.PIPE) 我正在从用户接受原始输入的IP和端口。 - Ashutosh Narayan
显示剩余4条评论

1
import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, error = p.communicate()

0
netstat -plant | awk '{print $4}' | grep %s:%s | wc -l

你可以使用Python来进行分割、过滤和计数:

process = subprocess.Popen(['netstat', '-plant'], stdout=subprocess.PIPE)

num_matches = 0

host_and_port = "%s:%s" % (ip, port)

for line in process.stdout:
    parts = line.split()
    if parts[3] == host_and_port: # or host_and_port in parts[3]
        num_matches += 1


print num_matches

这也解决了我的问题;但是@agf的答案只有一行。 - Ashutosh Narayan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接