我需要从 python 运行这个 linux 命令并将输出分配给一个变量。
ps -ef | grep rtptransmit | grep -v grep
我已经尝试使用 pythons 命令库来执行此操作。
import commands
a = commands.getoutput('ps -ef | grep rtptransmit | grep -v grep')
但是 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_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
有谁知道如何阻止输出被切断,或者有人可以建议另一种方法吗?
最佳答案
ps
显然限制了它的输出以适应终端的假定宽度。您可以使用 $COLUMNS
环境变量或使用 --columns
选项覆盖此宽度 ps
。
commands
模块已弃用。使用 subprocess
获取 ps -ef
的输出并在 Python 中过滤输出。不要像其他答案所建议的那样使用 shell=True
,在这种情况下它简直是多余的:
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
命令,您可以通过它直接搜索特定进程。
关于python - 从 python 运行 linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32966287/