2024-04-18 23:21:56 发布
网友
我试着从subprocess.call但到目前为止我还没有运气。我想用一些不同的子流程调用但这里有一个例子:
output = subprocess.call('vmstat -s, shell=True)
vmstat-s simple返回当前内存状态的列表。我想读取第2行(已用内存)并将其存储在一个变量中以供以后使用。在
在python中实现这一点的最佳方法是什么?在
谢谢你
使用check_output代替call:
check_output
call
>>> subprocess.check_output('vmstat -s', shell=True).splitlines()
或者,您可以使用管道stdout:
stdout
读取子进程stdout的通常方法是使用communicate方法。在
>>> from subprocess import Popen, PIPE >>> proc = Popen(['vmstat', '-s'], stdout=PIPE, stderr=PIPE) >>> stdout, _stderr = proc.communicate() >>> stdout.splitlines()[1] ' 13278652 K used memory'
请注意,这里不需要使用shell=True,并且在不需要时通常不鼓励使用它(这会带来不必要的开销,并且在某些情况下它可能会造成shell注入安全漏洞)。在
shell=True
使用
check_output
代替call
:或者,您可以使用管道
^{pr2}$stdout
:读取子进程stdout的通常方法是使用communicate方法。在
请注意,这里不需要使用
shell=True
,并且在不需要时通常不鼓励使用它(这会带来不必要的开销,并且在某些情况下它可能会造成shell注入安全漏洞)。在相关问题 更多 >
编程相关推荐