skywind3000 / PyStand

:rocket: Python Standalone Deploy Environment !!
MIT License
641 stars 75 forks source link

在不启用 -DPYSTAND_CONSOLE=ON 的时候,python 代码里的 sys.stdout.write 操作会让程序自动退出。 #38

Closed ghost closed 1 year ago

ghost commented 1 year ago

具体测试情况

skywind3000 commented 1 year ago

我这边没问题。 你贴一下 PyStand.int 这个入口脚本的内容,尽量删除无关代码,最小化复现。

ghost commented 1 year ago

我这儿可以用 PyStand-py38-pyqt5-lite 里面的例子PyStand.txt复现。 直接加一句 sys.stdout.write('_lib_path\n') 就够了。

myd7349 commented 1 year ago

我测了一下:https://github.com/myd7349/PyStand/commit/1fdae5913a12faaf97c8fa7dd157186a68a5fdde

在 GUI 模式下,不从控制台开你这个程序的话,AttachConsole 会失败,进而导致 PyStand 中内嵌的启动代码中的 stdout & stderr 重定向抛出异常。

用我魔改过的代码会看到:

图片

图片

解决思路 1:

在重定向失败时,尝试将 stdout & stderr 重定向到 nul,这样,即使用户代码包含诸如 stdout.write(...) 这样的代码,程序依然能运行。见:https://github.com/skywind3000/PyStand/pull/39

或者,重定向至一个文本文件,如:PyStand.log。

解决思路 2:

如果用户确实想用一个 GUI 版的 PyStand,但代码里还用到了 stdout,可以考虑 AllocConsole。

ghost commented 1 year ago

个人还是倾向于方案一,想看输出从 console 启动好了。双击跳出一个 console 看着碍眼,当然从命令行参数关掉 console 也行。

skywind3000 commented 1 year ago

倾向于方案1,不要加 log 了,真要加 log 的程序,一般会自己初始化 logging 库来做的。