Python - 使用Popen执行具有多个条件的查找

时间:2013-03-18 04:56:00

标签: python subprocess popen

我想在多个条件下执行find,例如:查找 foo ,不包括隐藏文件:

find . -type f \( -iname '*foo*' ! -name '.*' \)

Python代码:

import subprocess

cmd = ["find", ".", "-type", "f", "(", "-iname", "*foo*", "!", "-name", ".*", ")"]
sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print sp.communicate()[0].split()

有人可以解释我错过了什么吗?谢谢!

3 个答案:

答案 0 :(得分:1)

我也遇到了这个问题,我确定你现在已经知道了这个问题,但我想我还要权衡以防万一其他人遇到同样的问题。来发现,这是因为当你使用Popen时Python实际上在做什么(当使用shell = True时,python基本上只是使用/ bin / sh -c传递你的命令(Python's subprocess.Popen() results differ from command line?)。 shell默认为False,所以如果省略它或将其设置为False,将使用&b;可执行文件中指定的任何内容。文档在此处详细说明:https://docs.python.org/2/library/subprocess.html#subprocess.Popen

这些方面应该有效

import subprocess
cmd = 'find . -type f -iname "*foo*" ! -name ".*"'
sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print sp.communicate()[0].split()

答案 1 :(得分:0)

在python 3.7 subprocess.run()中,您可以将在空格上分割的cmd放到一个列表中,字符串就可以了。

subrocess.run()中没有文档。

我无法获得将命令扩展到列表中才能使用的功能,而字符串却正常工作。

cmd = "find . -type f -iname \*foo\* ! -name .\\*"
print(cmd)
ret = subprocess.run(cmd, shell=True, capture_output=True)
print(ret)

测试:

$ find . -type f -iname \*foo\* ! -name .\*
./foobar.txt
./barfoo.txt

$ ./findfoo.py
find . -type f -iname \*foo\* ! -name .\*
CompletedProcess(args='find . -type f -iname \\*foo\\* ! -name .\\*',
 returncode=0, stdout=b'./foobar.txt\n./barfoo.txt\n', stderr=b'')

答案 2 :(得分:-1)

至少,需要逃避*那里。

在第二个时候通过反斜杠转义(和)(将“\\(”和“\\)”传递给shell)

cmd = ["find", ".", "-type", "f", "\\(", "-iname", "\\*foo\\*", "!", "-name", ".\\*", "\\)"]

甚至只是摆脱那些(和) -

cmd = ["find", ".", "-type", "f", "-iname", "\\*foo\\*", "!", "-name", ".\\*"]

应该可以正常工作