Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a linux command from python

Tags:

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

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?

like image 212
DarylF Avatar asked Mar 16 '12 10:03

DarylF


People also ask

Can I run Linux command in Python?

Introduction. Python has a rich set of libraries that allow us to execute shell commands. The os. system() function allows users to execute commands in Python.

How do I run a Unix command in a Python script?

You cannot use UNIX commands in your Python script as if they were Python code, echo name is causing a syntax error because echo is not a built-in statement or function in Python. Instead, use print name . To run UNIX commands you will need to create a subprocess that runs the command.

How do you execute a command in Python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do I run multiple Linux commands in Python?

Run Multiple Commands at Once In Linux: You can use the | operator to concatenate two commands. The first command will list the files and folders in the directory, and the second command will print the output All the files and folders are listed.


1 Answers

#!/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 :-)

like image 120
sudhams reddy Avatar answered Sep 19 '22 16:09

sudhams reddy