Running a linux command from python

2020-02-04 21:36发布

问题:

I need to run this linux command from python and assign the output to a variable.

ps -ef | grep rtptransmit | grep -v grep

I've tried using pythons commands library to do this.

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

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'

but the expected output 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_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?

回答1:

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.

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)

You may also want to take a look the pgrep command by which you can directly search for specific processes.



回答2:

I usually use subprocess for running an external command. For your case, you can do something like the following

from subprocess import Popen, PIPE

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

The output will be in out variable.



回答3:

commands is deprecated, you should not use it. Use subprocess instead

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


回答4:

#!/usr/bin/python
import os

a = os.system("cat /var/log/syslog")

print a


from subprocess import call

b = call("ls -l", shell=True)

print b


import subprocess

cmd = subprocess.check_output('ps -ef | grep kernel', shell=True)

print cmd

Any of the above script will work for you :-)



回答5:

nano test.py
import os
a = os.system('ps -ef | grep rtptransmit | grep -v grep')
print(a)
python test.py
python3 test.py

Run python file using both python and python3

Run python script using python and python3



标签: python linux