[英]Show stdout with PyInstaller noconsole
如何使用 PyInstaller 創建一個也提供 CLI 的 GUI 應用程序,而不會彈出shell?
例如,如果我使用pyinstaller argparse_gui.py --noconsole
創建以下應用程序,則標准輸出不會顯示在 shell 中:
C:\projects\argparse_gui\dist\argparse_gui>argparse_gui.exe -V
C:\projects\argparse_gui\dist\argparse_gui>
我可以使用argparse_gui.exe -V > log.txt 2>&1
將 stdout/stderr 重定向到一個文件,但這並不完全是用戶友好的。 如果在沒有--noconsole
的情況下構建,我可以看到標准輸出,但是還有一個令人討厭的單獨 shell window。
# argparse_gui.py
import sys
import argparse
from PyQt5 import QtCore, QtWidgets, QtGui
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.init_widgets()
self.init_layout()
def init_widgets(self):
self.label = QtWidgets.QLabel('Hello, world!')
def init_layout(self):
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.label)
centralWidget = QtWidgets.QWidget()
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-V", "--version", help="display application information", action='store_true')
args = parser.parse_args()
if args.version:
print('Version 123', flush=True)
else:
app = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
編輯:我找到了一種迂回的方法,但控制台 window 會出現,直到 GUI 加載。 我將以下代碼放在主腳本的頂部,並在沒有 --windowed 的情況下運行 Pyinstaller。 如果腳本不是從現有控制台運行的,這將隱藏控制台 window。
import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
process_array = (ctypes.c_uint8 * 1)()
num_processes = kernel32.GetConsoleProcessList(process_array, 1)
if num_processes < 3: ctypes.WinDLL('user32').ShowWindow(kernel32.GetConsoleWindow(), 0)
否則,我將得出結論,沒有辦法使用 PyInstaller。 如果 --noconsole/--windowed,則 EXE 與pythonw
捆綁在一起。 PythonW 沒有附加控制台,即使從控制台啟動。
然而,命令行 arguments 仍然通過。 您仍然可以使用 sys.argv 或 argparser 來訪問它們。
在--noconsole
中運行時, sys.stdout
是NullWriter
object 並且sys.__stdout__
是None
。 在 1 上使用open()
會引發異常,CON 和 CONOUT$ 無法執行任何操作。 將控制台重定向到 >&1 會引發錯誤。
注意:在某些情況下,stdin、stdout 和 stderr 以及原始值stdin 、 stdout和stderr可以為 None。 對於未連接到控制台的 Windows GUI 應用程序和使用 pythonw 啟動的 Python 應用程序通常是這種情況。 https://docs.python.org/3/library/sys.html#sys.__stderr __
如果 EXE 是使用 --noconsole 構建的,那么 Pyinstaller 會顯式使用 PythonW.exe。 我無法找到解決此問題的方法,例如如果從 cli 調用,則加載控制台引導加載程序,否則加載 pythonw。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.