Python:文件未找到 [WinError 2] 系统找不到指定的文件,subprocess.py:1582。

13

详细错误信息:

 FileNotFoundError

  [WinError 2] The system cannot find the file specified

  at ~\AppData\Local\Programs\Python\Python39\lib\subprocess.py:1582 in _execute_child
      1578│             sys.audit("subprocess.Popen", executable, args, cwd, env)
      1579│ 
      1580│             # Start the process
      1581│             try:
    → 1582│                 hp, ht, pid, tid = _winapi.CreateProcess(
      1583│                     executable,
      1584│                     args,
      1585│                     # no special security
      1586│                     None,
make: *** [makefile:14: format] Error 1

我们在这里列出了类似的问题:https://bugs.python.org/issue17023

文件在那里,路径也没问题。 但是为什么我会得到这个错误,因为文件在指定位置呢?

运行格式化程序和编译器时,我遇到了这个错误。

4个回答

13
您只需要将 shell = True 设置并传递给您正在使用的子进程类即可。修改库文件会导致以后与其他程序员的代码存在兼容性问题。 为了更好地理解为什么我们需要设置此变量,请参阅文档: “对于所有调用,都需要 args,并且它应该是一个字符串或程序参数序列。通常建议提供参数序列,因为它允许模块处理任何所需的转义和引用参数(例如,允许文件名中有空格)。如果传递单个字符串,则必须将 shell 设为 True(请参见下文),否则字符串必须只能命名要执行的程序,而不指定任何参数。”

1
我遇到了这种错误,我意识到如果我使用pathlib.PureWindowsPath(<path>).as_posix()将Windows路径更改为posix风格,它就能正常工作。以下是我的操作步骤:
import subprocess as sp
import pathlib
import shlex

exe_path = r"C:\ffmpeg\bin\ffmpeg.exe"
print(f"exe path: {exe_path}")

try:
    cmd = f"{exe_path} -version"
    sp.Popen(shlex.split(cmd))
    sp.wait()
except FileNotFoundError as e:
    print(e)
    print("\n")

exe_path = pathlib.PureWindowsPath(exe_path).as_posix()
print(f"exe path: {exe_path}")

cmd = f"{exe_path} -version"
t=sp.Popen(shlex.split(cmd))
t.wait()

输出-->:

C:\Users\Veysel\Desktop>python file.py
exe path: C:\ffmpeg\bin\ffmpeg.exe
[WinError 2] The system cannot find the file specified

exe path: C:/ffmpeg/bin/ffmpeg.exe
ffmpeg version 2022-10-17-git-3bd0bf76fb-essentials_build-www.gyan.dev Copyright (c) 2000-2022 the FFmpeg developers

0

在我的环境中会产生错误的示例。

import concurrent.futures
import multiprocessing
import random
import subprocess


def worker(workerid):
    print(f"start {workerid}")
    p = subprocess.Popen(["sleep", f"{random.randint(1,30)}"])
    p.wait()
    print(f"stop {workerid}")
    return workerid


def main():
    tasks = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
        for i in range(20):
            tasks.append(pool.submit(worker, i))

        print("waiting for tasks...", flush=True)
        for task in concurrent.futures.as_completed(tasks):
            print(f"completed {task.result()}", flush=True)
        print("done.")


if __name__ == "__main__":
    main()

目前你的回答不够清晰。请编辑并添加更多细节,以帮助其他人理解它如何回答所提出的问题。你可以在帮助中心找到有关如何撰写好答案的更多信息。 - Community
这并没有真正回答问题。如果您有其他问题,可以通过点击[提问](https://stackoverflow.com/questions/ask)来提出。要在此问题获得新答案时收到通知,可以[关注该问题](https://meta.stackexchange.com/q/345661)。一旦您拥有足够的[声望](https://stackoverflow.com/help/whats-reputation),您也可以[添加赏金](https://stackoverflow.com/help/privileges/set-bounties)以引起更多注意。- [来自审核](/review/late-answers/33690439) - hlongmore

-3
重要提示:如果对库文件进行任何修改,可能会导致与其他程序员的代码后续兼容性问题。如需更多信息,请参阅官方文档,此处提供适当的链接
由于这个错误给我的工作带来了麻烦,我现在采用以下解决方案,一切都很好。
解决此错误的方法是: 我们必须修改您环境中的subprocess.py文件。
首先,您必须找到此文件,然后进行编辑。 在我的电脑上,它的位置是-C:\Users\User\AppData\Local\Programs\Python\Python39\Lib。
在这段代码中:
def __init__(self, args, bufsize=-1, executable=None,
             stdin=None, stdout=None, stderr=None,
             preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
             shell=True, cwd=None, env=None, universal_newlines=False,
             startupinfo=None, creationflags=0,
             restore_signals=True, start_new_session=False,
             pass_fds=(), *, encoding=None, errors=None):

你需要改变shell的值。
shell=False改为shell=True

这个解决方案对我有用,希望对你也有用。

谢谢。


3
这是一个非常非常非常糟糕的想法。不要去修改已经安装在你的系统上的核心Python库,以避免修复你自己应用程序中的错误。 - shadowtalker
1
好的。感谢您的反馈。 请提供一个好的解决方案来解决这个错误。 - Lakshay Rohilla
1
没有看到您的实际代码,我们无法回答这个问题。请先阅读:https://stackoverflow.com/help/minimal-reproducible-example - shadowtalker
请注意,您提供的Python错误链接已被关闭,因为它不被认为是一个错误,仅涉及特定情况。如果没有看到您的代码,就无法确定您的情况是否相同。 - shadowtalker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接