如何从基于 Python(tkinter) 的 exe 文件执行 shell 命令?

How to execute shell commands from Python(tkinter) based exe file?

我正在尝试从基于 tkinter 的 Python 应用程序触发一些 shell 命令,使用以下代码:

from tkinter import *
import subprocess

win = Tk()

def runScript():    
    result = subprocess.run(
        ["echo", "hello"], capture_output=True, text=True
    )
    outputLabel = Label(win, text=result.stdout)
    outputLabel.grid(row=1, column=0)
    

# Button 
submitButton = Button(win, text="Submit", command=runScript)
# Implementing 
submitButton.grid(row=0, column=0)

#Set the geometry of tkinter frame
win.geometry("250x250")

win.mainloop()

当 运行 来自 shell 的 py 应用程序时,命令执行正常。 但是用下面的命令生成exe时pyinstaller --onefile -w filename.py,命令好像没有执行。

subprocess 是 --windowed 导致破损的情况。

您应该明确地将未使用的标准输入和标准错误重定向到 NULL。 您必须设置 shell=True。当您希望执行的命令内置于 shell.

时使用
result = subprocess.run(["echo", "hello"],  text=True, shell=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

您现在可以使用 pyinstaller --onefile -w filename.py

这里是 exe 文件的输出: