在Python子进程内部查找返回1

2024-06-11 23:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用以下GNUfind命令搜索目录的内容:

find path -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

输出:

^{pr2}$

奇怪的是,CalledProcessError对象输出属性与我在Linux shell中运行find时得到的输出完全相同(返回的输出大约有15K行)。我也试过设置bufsize=-1,但没用。在

对理解这种行为有什么建议吗?在

我使用的是python2.7.2,find版本是4.2.20。在


Tags: 代码nameimport命令outputlinuxtypefind
3条回答

如果使用plumbum,任务将简单到:

from plumbum.cmd import find
cmd = find['/remote/scratch/results']['-type', 'f']['-name','QUEUED']['-o']['-name', 'run.pid']['-o']['-name', 'PID']
cmd() # run it

你不必担心逃跑,我猜这是你麻烦的原因。在

尽管您发现了问题,对于您正在尝试实现的如此简单的事情,我不会使用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

似乎在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时删除操作似乎是问题的根本原因。在

相关问题 更多 >