Python中的Bash反引号的等价

Python和Python中的反引号是什么? 也就是说,在Ruby中我可以这样做:

foo = `cat /tmp/baz` 

Python中的等价语句是什么样的? 我已经尝试了os.system("cat /tmp/baz")但是将结果标准化并返回给我该操作的错误代码。

 output = os.popen('cat /tmp/baz').read() 

最灵活的方法是使用subprocess模块:

 import subprocess proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE) (out, err) = proc.communicate() print "program output:", out 

如果要通过shell传递呼叫,例如使用*来获取文件名扩展,则可以使用shell=True参数。 如果你这样做,你必须提供命令作为一个string,引用/ …就像你会在shell提示符下键入它:

 proc = subprocess.Popen('cat /tmp/ba* "spac e.txt"', shell=True, ...) 

某事是正确的 。 你也可以使用os.popen(),但是在可用的地方(Python 2.4+)subprocess通常是可取的。

然而,与鼓励它的一些语言不同,通常认为产生一个可以在语言中完成同样工作的子过程是一种糟糕的forms。 速度较慢,不太可靠并且取决于平台。 你的例子会更好:

 foo= open('/tmp/baz').read() 

ETA:

巴兹是一个目录,我试图获取该目录中的所有文件的内容

? 目录上的猫给我一个错误。

如果你想要一个文件列表:

 import os foo= os.listdir('/tmp/baz') 

如果你想要一个目录中的所有文件的内容,如:

 contents= [] for leaf in os.listdir('/tmp/baz'): path= os.path.join('/tmp/baz', leaf) if os.path.isfile(path): contents.append(open(path, 'rb').read()) foo= ''.join(contents) 

或者,如果你能确定那里没有目录,那么你可以把它放在一行中:

 path= '/tmp/baz' foo= ''.join(open(os.path.join(path, child), 'rb').read() for child in os.listdir(path)) 
 foo = subprocess.check_output(["cat", "/tmp/baz"]) 

最简单的方法就是使用命令包。

 import commands commands.getoutput("whoami") 

输出:

'bganesan'

 import os foo = os.popen('cat /tmp/baz', 'r').read() 

从Python 3.5开始,推荐的方法是使用subprocess.run 。 为了得到和你描述的相同的行为,你可以使用:

 output = subprocess.run("ls", shell=True, stdout=subprocess.PIPE).stdout 

这将返回一个bytes对象。 你可能想追加.decode("ascii").decode("utf-8")到最后得到一个str

我在用着

(6:0)$ python –version Python 2.7.1

上面的例子之一是:

 import subprocess proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print "program output:", out 

对于我来说,无法访问目录/ tmp。 在查看我replace的subprocess的文档string后

[“prog”,“arg”]

“编程”

并获得了所需的shell扩展行为(Perl的`prog arg`)

print subprocess.Popen(“ls -ld / tmp / v *”,stdout = subprocess.PIPE,shell = True).communicate()[0]


我退出使用python了,因为我很烦的做了相当于perl`cmd …`的困难。 我很高兴地发现Python已经使这个合理。

如果使用subprocess.Popen,请记住指定bufsize。 默认值是0,意思是“无缓冲”,而不是“select一个合理的默认值”。

这在python3中不起作用,但是在python2中,你可以用一个自定义的__repr__方法来扩展str ,这个方法调用你的shell命令,并像下面这样返回它:

 #!/usr/bin/env python import os class Command(str): """Call system commands""" def __repr__(cmd): return os.popen(cmd).read() 

你可以使用像

 #!/usr/bin/env python from command import Command who_i_am = `Command('whoami')` # Or predeclare your shell command strings whoami = Command('whoami') who_i_am = `whoami`