按目录中的子进程搜索和 return 非零错误

search by subproces in dir and return non-zero error

我想制作一个程序来搜索我所有的电脑并制作结果列表,所以首先我不能一起搜索所有分区并且必须使用 os.chdir("") 另一方面当一些后缀剂量时不在其中退出会出错并停止程序。

我的代码:

os.chdir("E:\")
txt = subprocess.check_output("dir /S /B *.txt" , shell=True).decode().split()
dll = subprocess.check_output("dir /S /B *.dll" , shell=True).decode().split()
png = subprocess.check_output("dir /S /B *.png" , shell=True).decode().split()
gif = subprocess.check_output("dir /S /B *.gif" , shell=True).decode().split()
tlb = subprocess.check_output("dir /S /B *.tlb" , shell=True).decode().split()

ALL = txt + dll + png + gif + tlb

结果:

File Not Found
Traceback (most recent call last):
  File "e:\code\lock\debug.py", line 12, in <module>
    png = subprocess.check_output("dir /S /B *.png" , shell=True).decode().split()
  File "C:\Users332668\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Users332668\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 524, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command 'dir /S /B *.png' returned non-zero exit status 1. 

我应该如何调试和改进我的代码!!

你的问题是你正在使用 check_output() 如果命令 returns 是一个非零错误代码,它将引发异常,如果 dir 没有找到匹配的文件,它会引发异常。

如果您不在意,您应该使用 getoutput

然而,这里真的没有必要 shell 输出到 dir 5 次——只需使用 os.walk():

import os
EXTENSIONS = {".txt", ".dll", ".png", ".gif", ".tlb"}
found_files = []
for dirname, dirpaths, filenames in os.walk("E:\"):
    for filename in filenames:
        ext = os.path.splitext(filename)[-1]
        if ext in EXTENSIONS:
            found_files.append(os.path.join(dirname, filename))

for file in found_files:
    print(file)