Running linux command from python

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

ps -ef | grep rtptransmit | grep -v grep 

I tried using the pythons command library for this.

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

But a ends the circumcision. 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 expected result:

 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 circumcision or can someone suggest a different method?

+7
source share
3 answers

ps apparently limits its output to fit into the intended width of the terminal. You can override this width with the $COLUMNS environment $COLUMNS or with the --columns option to ps .

The commands module is deprecated. Use subprocess to get the result of ps -ef and filter the output in Python. Do not use shell=True , as suggested by other answers, in this case it is simply superfluous:

 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 can also view the pgrep command, with which you can directly search for specific processes.

+8
source

commands 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
source

I usually use subprocess to run 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 the variable out .

+3
source

All Articles