python - 如何从基于 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
,这些命令似乎没有执行。
解决方案
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文件的输出:
推荐阅读
- r - 如何在 R 中成功制作带有图例的轮廓增强漏斗图?
- python - 使用 to_datetime pandas 方法时,对象是不可分割的错误
- python - 如何展平熊猫数据框?
- azure - Kubernetes - 我们可以为两个集群节点 - Windows 和 Linux 使用相同的挂载卷(文件共享)吗?
- python - 没有市场的 github 操作 pyenv
- reactjs - Redux:访问组件外部的存储
- joomla3.0 - 在 Joomla 前端编辑文章时呈现特定的自定义字段
- angular - 为什么 dataSource 没有显示在我的 mat-table 中?
- python - 序数回归算法似乎将预测转移了一类
- angular - Firebase 身份验证 RxJs 的嵌套排气映射和连接映射