详细错误信息:-
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
文件在那里,路径也很好。 但是,当文件位于指定位置时,为什么我会收到此错误?
我在运行格式化程序 linter 时遇到此错误。
您只需设置 shell = True 并将其传递给您正在使用的子流程类。修改库文件会导致以后与其他程序员的代码发生兼容性问题。 要深入了解为什么我们需要设置此变量,请查看文档: “args 对于所有调用都是必需的,并且应该是字符串或程序参数序列。通常首选提供参数序列,因为它允许模块处理任何所需的参数转义和引用(例如,允许文件名中的空格)。如果传递单个字符串,则 shell 必须为 True(见下文),否则该字符串必须简单地命名要执行的程序,而不指定任何参数。”
我遇到了这种错误,我意识到如果我使用
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
就我而言,我发现出现这种情况是因为 ffmpeg 安装在“C:program file...”中,这意味着它需要权限。
有两种方法可以解决。
重要提示:- 如果对库文件进行任何修改,可能会导致其他程序员的代码稍后出现兼容性问题。 要获取更多有关为 shell 设置值的必要性的信息,请参阅官方文档,此处提供了正确的链接。
由于这个错误给我的工作带来了麻烦,我现在执行了以下解决方案,一切正常。
要解决此错误:- 我们必须修改您环境中的
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
。
这个解决方案对我有用,我希望它也对你有用。
谢谢你。