从python运行一个linux命令

我需要从python运行这个linux命令,并将输出分配给一个variables。

ps -ef | grep rtptransmit | grep -v grep 

我试过使用pythons命令库来做到这一点。

 import commands a = commands.getoutput('ps -ef | grep rtptransmit | grep -v grep') 

但是一切都结束了。 我得到的输出是:

 '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命令。

commands已被弃用,您不应该使用它。 改用subprocess

 import subprocess a = subprocess.check_output('ps -ef | grep rtptransmit | grep -v grep', shell=True) 

我通常使用subprocess来运行一个外部命令。 对于你的情况,你可以做如下的事情

 from subprocess import Popen, PIPE p = Popen('ps -ef | grep rtptransmit | grep -v grep', shell=True, stdout=PIPE, stderr=PIPE) out, err = p.communicate() 

输出将在变量。