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

Python打包为可执行文件时出现subprocess.py FileNotFoundError,pip包运行正常

问题分析与解决方案

错误原因

  1. 跨平台命令不兼容:你使用的ls命令仅在Linux/macOS或类Unix环境(如WSL、Git Bash)中存在,Windows系统原生没有该命令。打包后的可执行文件直接调用Windows终端(cmd),自然找不到ls;而pip安装运行正常,大概率是你当时在类Unix环境下测试的。
  2. 路径传递问题:虽然Python 3.6+支持直接将pathlib.Path对象传入subprocess.run,但打包后的环境可能存在兼容性问题,显式将路径转为字符串更稳妥。

解决方法

方法1:用Python原生API替代shell命令(推荐)

完全不需要调用外部命令,直接用pathlib的方法获取目录内容,跨平台且更可靠:

import pathlib
import appdirs

files_path = pathlib.Path(appdirs.user_data_dir(appname="my_app"))
# 遍历目录下的所有条目
for item in files_path.iterdir():
    item_type = "目录" if item.is_dir() else "文件"
    print(f"{item.name} ({item_type})")

# 如果需要更详细的文件信息(比如权限、大小),可以用stat()方法
for item in files_path.iterdir():
    stat_info = item.stat()
    print(f"{item.name}: 大小{stat_info.st_size}字节, 修改时间{stat_info.st_mtime}")

方法2:适配不同系统的shell命令

如果一定要用外部命令,需根据操作系统选择对应命令,并将路径转为字符串:

import sys
import pathlib
import subprocess
import appdirs

files_path = pathlib.Path(appdirs.user_data_dir(appname="my_app"))
files_path_str = str(files_path)

# 根据操作系统选择命令
if sys.platform.startswith("win32"):
    # Windows用dir命令,/q显示所有者,/w宽格式显示
    subprocess.run(["cmd", "/c", "dir", files_path_str, "/q", "/w"], check=True)
else:
    # Linux/macOS用ls命令
    subprocess.run(["ls", "-la", files_path_str], check=True)

注:Windows下必须通过cmd /c执行dir命令,因为它是cmd内置命令,并非独立可执行文件。

额外提醒

  • 打包可执行文件时,优先用Python原生API实现功能,减少对外部系统命令的依赖,避免环境差异导致的问题。
  • 测试Windows可执行文件时,要在纯Windows环境下运行,不要在WSL或Git Bash中测试,否则会误判命令兼容性。

内容的提问来源于stack exchange,提问作者Adib Baji

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:11:09