V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ShihanW
V2EX  ›  Python

Python 使用 pyinstaller 打包命令行脚本为 exe 后报错

  •  
  •   ShihanW · 101 天前 · 1064 次点击
    这是一个创建于 101 天前的主题,其中的信息可能已经有所发展或是发生改变。

    写了一个 python 命令行脚本,在 cmd 使用 python 调用运行正常,但是用 pyinstaller 打包成 win 的可执行程序就报错了,截图如下,

    image-20240117131037938

    看好像是 argparse 导致,百度谷歌翻了一遍没找到解决办法,V 友能帮忙看看吗。

    6 条回复    2024-01-17 13:44:08 +08:00
    tomczhen
        1
    tomczhen  
       101 天前 via Android
    等老夫算一卦看看 bug 出在哪里。
    orzfly
        2
    orzfly  
       101 天前
    我不写 python ,但你这看起来打包成 Windows GUI 程序了,我猜是 sys.stdout / sys.stderr 是空的了。
    fields
        3
    fields  
       101 天前
    直接执行可以但是打包执行报错,这错误信息看不出来什么引起的,给个源码来链接,大家给你看一下
    你是不是有动态导入其他库啊
    lovelylain
        4
    lovelylain  
       101 天前 via Android
    def _print_message(self, message, file=None):
    if message:
    file = file or _sys.stderr
    try:
    file.write(message)
    except (AttributeError, OSError):
    pass

    @orzfly 你是对的
    Vegetable
        5
    Vegetable  
       101 天前
    至少在 py3.11 里这个报错已经被捕获了, 从 py2.7 的代码来看,这地方尝试写 file or sys.stderr ,因此可以确定是 sys.stderr 为 None 导致的。
    看起来这是 argparse 这个包的设计问题,
    可以考虑升级 python 版本,当然这个有点伤筋动骨
    可以考虑移除 argparse 的依赖
    可以考虑 https://stackoverflow.com/questions/29935283/how-to-set-custom-output-handlers-for-argparse-in-python 魔改 argparse ,其实也只要改一个方法
    ShihanW
        6
    ShihanW  
    OP
       101 天前
    @fields
    @lovelylain
    @Vegetable
    @tomczhen
    @orzfly
    感谢大家的留言,是我打包方式有问题,@orzfly 确实是打包成 GUI 程序了, 把打包命令-w 去掉就行
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2797 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:41 · PVG 14:41 · LAX 23:41 · JFK 02:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.