从python运行linux命令 [英] Running a linux command from python
问题描述
我需要从python运行此linux命令,并将输出分配给变量.
I need to run this linux command from python and assign the output to a variable.
ps -ef | grep rtptransmit | grep -v grep
我尝试使用pythons命令库执行此操作.
I've tried using pythons commands library to do this.
import commands
a = commands.getoutput('ps -ef | grep rtptransmit | grep -v grep')
但是a结束了.我得到的输出是:
But a gets the end of cut off. The output I get is:
'nvr 20714 20711 0 10:39 ? 00:00:00 /opt/americandynamics/venvr/bin/rtptransmit setup_req db=media camera=6 stream=video substream=1 client_a'
但预期的输出是:
nvr 20714 20711 0 10:39 ? 00:00:00 /opt/americandynamics/venvr/bin/rtptransmit setup_req db=media camera=6 stream=video substream=1 client_address=192.168.200.179 client_rtp_port=6970 override_lockout=1 clienttype=1
有人知道如何阻止输出中断吗?有人可以建议其他方法吗?
Does anyone know how to stop the output from getting cut off or can anyone suggest another method?
推荐答案
ps
显然限制了其输出以适合终端的假定宽度.您可以使用$COLUMNS
环境变量或ps
的--columns
选项覆盖此宽度.
ps
apparently limits its output to fit into the presumed width of the terminal. You can override this width with the $COLUMNS
environment variable or with the --columns
option to ps
.
不推荐使用commands
模块.使用subprocess
获取ps -ef
的输出,并在Python中过滤输出.请勿使用其他答案建议的shell=True
,在这种情况下,它只是多余的:
The commands
module is deprecated. Use subprocess
to get the output of ps -ef
and filter the output in Python. Do not use shell=True
as suggested by other answers, it is simply superfluous in this case:
ps = subprocess.Popen(['ps', '-ef', '--columns', '1000'], stdout=subprocess.PIPE)
output = ps.communicate()[0]
for line in output.splitlines():
if 'rtptransmit' in line:
print(line)
您可能还想看看pgrep
命令,通过它可以直接搜索特定进程.
You may also want to take a look the pgrep
command by which you can directly search for specific processes.
这篇关于从python运行linux命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!