在Python子流程中查找返回1
我需要使用以下GNU在Python子流程中查找返回1,python,find,Python,Find,我需要使用以下GNUfind命令搜索目录的内容: 查找路径-type f-name file1-o-name file2-o-name file3 在Linux shell中执行此命令时,find命令返回,退出代码为0。当我在子流程调用中执行相同的命令时,find命令返回退出代码1: import subprocess import shlex findcmd = "/depot/findutils/bin/find /remote/scratch/results -type f -na
find
命令搜索目录的内容:
查找路径-type f-name file1-o-name file2-o-name file3
在Linux shell中执行此命令时,find
命令返回,退出代码为0。当我在子流程调用中执行相同的命令时,find
命令返回退出代码1:
import subprocess
import shlex
findcmd = "/depot/findutils/bin/find /remote/scratch/results -type f -name 'QUEUED' -o -name 'run.pid' -o -name 'PID'"
try:
output = subprocess.check_output(shlex.split(findcmd))
except subprocess.CalledProcessError, cpe:
print cpe.output
raise cpe
输出:
Traceback (most recent call last):
File "./getaverages.py", line 63, in <module>
raise cpe
subprocess.CalledProcessError: Command '['/depot/findutils/bin/find', '/remote/scratch/results', '-type', 'f', '-name', 'QUEUED', '-o', '-name', 'run.pid', '-o', '-name', 'PID']' returned non-zero exit status 1
回溯(最近一次呼叫最后一次):
文件“/getaverages.py”,第63行,在
提高cpe
subprocess.CalledProcessError:命令“[”/depot/findutils/bin/find',“/remote/scratch/results',“-type”,“f',“-name”,“QUEUED',”-o',“-name”,“run.pid',“-o',“-name”,“pid']”返回非零退出状态1
奇怪的是,CalledProcessError
对象输出atribute的输出与我在Linux shell中运行find
时得到的输出完全相同(返回的输出大约有15K行)。我还尝试将bufsize设置为-1,但没有效果
对理解这种行为有什么建议吗
我使用的是Python 2.7.2和find
版本是4.2.20。如果使用,任务将非常简单:
from plumbum.cmd import find
cmd = find['/remote/scratch/results']['-type', 'f']['-name','QUEUED']['-o']['-name', 'run.pid']['-o']['-name', 'PID']
cmd() # run it
<>你不必担心逃跑,我猜是你麻烦的原因。
似乎在15K输出的中间,我错过了以下几行:
/depot/findutils/bin/find: /remote/scratch/results/tmp.na.8Em5fZ: No such file or directory
/depot/findutils/bin/find: /remote/scratch/results/tmp.na.k6iHJA: No such file or directory
/depot/findutils/bin/find: /remote/scratch/results/tmp.na.ZPe2TC: No such file or directory
事实证明,我正在搜索的路径包含模拟结果,对于超过3天的文件,它会定期被删除。当执行
find
时发生删除,似乎是问题的根本原因。尽管您发现了问题,但对于您试图实现的这么简单的事情,我不会放弃,而是使用os.walk
:
import os, os.path
search = 'file1 file2 file3'.split()
for root, dirs, files in os.walk('/path'):
for f in filter(lambda x: x in search, files):
# do something here
fn = os.path.join(root, f)
print 'FOUND', fn
我总是更倾向于使用find(或者通常是GNU/Linux命令),因为:1)Python代码变得更紧凑,2)在shell中测试输入/输出通常更容易,而不是在更大的Python程序中隔离输入/输出,3)执行速度似乎更快(尽管这更像是一种印象,而不是基于事实)。不过,谢谢你的提示。如果你是这么想的,那你为什么不使用shell脚本呢?我的意思是在Python脚本中使用一些好的shell工具,而不是在Python中做任何事情。无论什么让你抓狂。。。但是,如果您真的关心速度,那么可以使用python中的多线程来加快速度。例如,一个线程执行行走(生产者),另一个线程执行处理(消费者)。另外一个好处是,它可以跨平台工作,因为即使是不同的*NIX平台也有不兼容的
find
实现。