Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing shell backquote in python?

Tags:

python

I am translating bash scripts into python for some reasons.

Python is more powerfull, nevertheless, it is much more harder to code simple bash code like this :

MYVAR = `grep -c myfile`

With python I have first to define a backquote function could be :

def backquote(cmd,noErrorCode=(0,),output=PIPE,errout=PIPE):
    p=Popen(cmd, stdout=output, stderr=errout)
    comm=p.communicate()
    if p.returncode not in noErrorCode:
        raise OSError, comm[1]
    if comm[0]:
        return comm[0].rstrip().split('\n')

That is boring !

Is there a Python's flavor (IPython ?) where it is easy to spawn process and get back the output ?

like image 838
Eric Avatar asked Dec 07 '22 22:12

Eric


2 Answers

In Python 2.7 or above, there is subprocess.check_output() which basically does what you are after.

like image 95
Sven Marnach Avatar answered Dec 21 '22 17:12

Sven Marnach


The os.subprocess documentation describes how to replace backquotes:

output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
like image 39
Andrea Spadaccini Avatar answered Dec 21 '22 19:12

Andrea Spadaccini