由于某些原因,我正在将bash脚本翻译成python。
Python更强大,但是,像这样编写简单的bash代码要困难得多:
MYVAR = `grep -c myfile`
使用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')
这很无聊!
是否有Python的风格(IPython?),很容易产生进程并返回输出?
答案 0 :(得分:9)
在Python 2.7或更高版本中,subprocess.check_output()
基本上可以满足您的需求。
答案 1 :(得分:4)
os.subprocess documentation描述了如何替换反引号:
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
答案 2 :(得分:2)
定义了这个backquote
函数后,您可以从程序以及交互式shell(IPython等)中反复调用它。
在Python和IMHO中没有直接使用这种“反引号”的原因。 Python以其可读性而闻名,并且在该语言中使用这样的构造会鼓励不可读的“scriptish”代码。话虽如此,backquote
可能不是返回子进程输出的函数的最具描述性的名称。
答案 3 :(得分:0)
正如Andrea所说,你应该使用subprocess.Popen - 无需扩展输入 - 您可以在单独的文件中执行此操作, 说你在脚本中导入的“helper.py”:
from subprocess import Popen, PIPE
def r(cmd_line):
return Popen(cmd_line.split(), stdout=PIPE).communicate()[0]
在你的其他文件上,你可以做到
from helper import r
print r("ls -l")
print r("pwd")
r("tar czvf new_tarball.tar.gz %s" % path_to_archive)
请注意,如果必须传递空格,则此简化方法将无效
在shell命令的参数内 - 就像“我的文档”参数一样 -
在这种情况下,要么显式使用Popen,要么增强辅助函数
它可以处理它。用“\”简单地逃离白色空间即可
被split
我忽略了。