Arghya
Arghya

Reputation: 250

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

I'm trying to trigger some shell commands from a tkinter based Python app, using the following code:

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()

The commands are executing fine when running the py app from the shell. However, when the exe is generated using the following command pyinstaller --onefile -w filename.py, the commands don't seem to execute.

Upvotes: 1

Views: 489

Answers (1)

Kartikeya
Kartikeya

Reputation: 838

subprocess is a case where --windowed leads to breakages.

You should explicitly redirect the unused stdin and stderr to NULL. You must set shell=True. This is used when the command you wish to execute is built into the shell.

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

You can now use pyinstaller --onefile -w filename.py

Here is the output of the exe file now:

Output of executable now

Upvotes: 2

Related Questions