You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python subprocess.run报FileNotFoundError的解决方法求助

解决subprocess调用时的FileNotFoundError错误

问题场景

我正在开发一款使用Youtube Data API的Python应用,编写了如下代码:

import os
from subprocess import run
os.chdir(os.path.dirname(__file__))
command = 'python3.10 uploadYoutube.py --file="blank.mp4" --title="Blank" --description="THIS IS YOUR BLANK VIDEO" --keywords="blank" --category="20" --privacyStatus="private"'
terminal_output = run(command, capture_output=True).stdout 
print(terminal_output)

运行代码时出现如下错误:

terminal_output = run(command, capture_output=True).stdout
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 503, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 971, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\subprocess.py", line 1456, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

解决方法

  • 改用参数列表传递命令
    Windows系统下,subprocess.run解析字符串命令时容易出现路径和参数识别错误,最可靠的方式是将命令拆分为参数列表。修改后的代码:
import os
from subprocess import run
os.chdir(os.path.dirname(__file__))
# 拆分命令为独立参数,无需额外引号转义
command = [
    'python3.10', 
    'uploadYoutube.py', 
    '--file=blank.mp4', 
    '--title=Blank', 
    '--description=THIS IS YOUR BLANK VIDEO', 
    '--keywords=blank', 
    '--category=20', 
    '--privacyStatus=private'
]
# 添加text=True将输出转为字符串(可选,提升可读性)
terminal_output = run(command, capture_output=True, text=True).stdout 
print(terminal_output)

这种方式让系统直接识别每个参数,避免了字符串解析时的路径查找问题。

  • 验证Python可执行文件路径
    如果系统PATH中没有python3.10,需要替换为Python可执行文件的完整绝对路径,例如:
command = [
    'C:/Program Files/Python310/python.exe',
    # 其余参数不变
]
  • 确认目标文件存在
    确保uploadYoutube.py和blank.mp4确实位于当前脚本所在目录(os.chdir切换后的路径),如果不在,需使用它们的完整绝对路径。

内容的提问来源于stack exchange,提问作者Zak Virgo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:17:36