首页 > 解决方案 > 如何从基于 Python(tkinter)的 exe 文件执行 shell 命令?

问题描述

我正在尝试使用以下代码从基于 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,这些命令似乎没有执行。

标签: pythonpython-3.xtkintersubprocess

解决方案


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文件的输出:

现在可执行文件的输出


推荐阅读