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 ?
In Python 2.7 or above, there is subprocess.check_output()
which basically does what you are after.
The os.subprocess documentation describes how to replace backquotes:
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With