在python中做shell反引用?

Eri*_*ric 4 python

我出于某些原因将bash脚本翻译成python.

Python更强大,但是,编写这样的简单bash代码要困难得多:

MYVAR = `grep -c myfile`
Run Code Online (Sandbox Code Playgroud)

使用python我首先要定义一个反引号函数可以是:

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')
Run Code Online (Sandbox Code Playgroud)

那太无聊了!

有没有Python的味道(IPython?),很容易产生进程并获得输出?

Sve*_*ach 9

在Python 2.7或更高版本中,subprocess.check_output()基本上可以实现您的目标.