开发者

Doing shell backquote in python?

开发者 https://www.devze.com 2023-02-18 21:26 出处:网络
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 :

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,),out开发者_StackOverflowput=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]


Having defined this backquote function you can just call it again and again, from your programs as well as the interactive shell (IPython, etc).

There's no direct way to use such "backquotes" in Python, and IMHO for a good reason. Python is known for its readability, and having such a construct in the language encourages unreadable "scriptish" code. Having said that, backquote is probably not the most descriptive name for a function that returns the output of a subprocess.


As Andrea put it, you should use subprocess.Popen - No need however for the extended typing -You can do this in a separate file, say "helper.py" that you import in your scripts:

from subprocess import Popen, PIPE

def r(cmd_line):
    return Popen(cmd_line.split(), stdout=PIPE).communicate()[0]

And on your other files, you can do just

from helper import r

print r("ls -l")
print r("pwd")
r("tar czvf new_tarball.tar.gz %s" % path_to_archive)

Note that this simplified way won't work if you have to pass white space inside a parameter to the shell command - like a "My Documents" parameter - in that case, either use Popen explicitly, or enhance the helper function so that it can handle it. SImply escaping the white space with "\" will be ignored by the split I am using there.

0

精彩评论

暂无评论...
验证码 换一张
取 消