文件未找到错误:子流程.Popen(['dir'](Windows 7)

2024-04-25 00:22:33 发布

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

我在为shell命令使用subprocess.Popen,因为与subprocess.run相比,它在管道方面的灵活性更强

我从一些简单的例子开始,但是我得到了FileNotFoundError:

有人告诉我,如果我将参数作为正确的列表,则shell = True是不必要的。但是它似乎不起作用。在

以下是我的尝试:

import subprocess
p1 =subprocess.Popen(['dir'], stdout =subprocess.PIPE)

output = p1.communicate[0]


p = subprocess.Popen([ "dir", "c:\\Users"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outputs = p.communicate()

两者都会导致FileNotFoundError


Tags: run命令参数管道dirstdoutshell例子
3条回答

试试这个(在windows上):

import subprocess

file_name = "test.txt"

sp = subprocess.Popen(["cmd", "/c", 'dir', '/s', '/p', file_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = sp.communicate()
output = output[1].decode()

if file_name in output:
    print("yes")
else:
    print("no")

在Linux上,替换对子进程的调用,如下所示:

^{pr2}$

我想钥匙在:stdout=subprocess.PIPE, stderr=subprocess.PIPE

由于dir只是cmd.exe(或powershell.exe)理解的命令,因此您可以:

subprocess.Popen(["cmd", "/c", "dir", "c:\\Users"], stdout=subprocess.PIPE)

对应于在shell中执行以下操作

^{pr2}$

您可能会发现您必须完全路径cmd,如c:\\Windows\\System32\\cmd.exe

你的问题是“dir”是一个Windows内部命令,而你的“popen”则在寻找可执行文件的名称。你可以尝试设置一个“bat方向文件,该文件运行“dir”命令以查看此命令是否有效,或者只需尝试\Windows\system32中的任何命令。在

相关问题 更多 >