【问题标题】:search by subproces in dir and return non-zero error按 dir 中的子进程搜索并返回非零错误
【发布时间】:2021-02-01 07:12:18
【问题描述】:

我想制作一个程序来搜索我所有的电脑并列出结果,所以首先我不能一起搜索所有分区并且必须使用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:\Users\81332668\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Users\81332668\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. 

我应该做些什么来调试和改进我的代码!!

【问题讨论】:

    标签: python python-3.x cmd subprocess


    【解决方案1】:

    您的问题是您正在使用check_output(),如果该命令返回非零错误代码,它将引发异常,并且 dir 如果找不到匹配的文件,则会执行此操作。

    如果你不关心这个,你应该使用getoutput

    但是,这里真的没有必要向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)
    

    【讨论】:

    • 老兄,你的代码可以工作,但我想把所有结果放在一个列表中,尽管你的代码把每个结果都放在了每个列表中,你也可以改进一下吗?
    • @m7.arman 我的代码没有在任何列表中添加任何内容,但现在可以了。
    • 在最后一行我必须打印 found_file 。无论如何谢谢你解决我的错误
    • 老兄,我有一个关于环的问题,我可以这样编码:.. os.walk("E:\\"and"C:\\"): 我想我试试只回复结果就出错
    • 如果您需要多个根,则需要为此添加另一个循环:for root in ("E:\\", "C:\\"): for dirname, dirpaths, filenames in os.walk(root): 等。
    猜你喜欢
    • 2016-12-11
    • 2014-09-23
    • 2015-03-11
    • 2012-01-17
    • 2020-10-24
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多