Search code examples
pythonuser-interfacewindows-console

run command from Python and then close


I am trying to build a small shell application, which runs a command from a GUI application. When I press the "off" button, the console for the command should be closed. I have two questions:

  1. When I run the command, the command is running on the same console as my Python script. How can I open the command in a new console?

  2. How can I stop the command? I mean like if the command is working in the same process as the GUI, I can just use exit(), but then the entire program will be terminated.

This is my code so far:

from tkinter import *
import subprocess
import os

top = Tk()

def turnOn():
    p = subprocess.Popen("ping stackoverflow.com")

def turnOff():
    pass
    #should i do: p.close() of something?

on = Button(top, text = "on", command = turnOn)
off = Button(top, text = "off", command = turnOff)

on.grid()
off.grid()
top.mainloop()

Solution

  • You can stop the command by calling the subprocess's .terminate method. Here's a crude example that uses a global variable to store the Popen object; it would be better to wrap the GUI in a class, and store proc as an instance attribute of that class.

    import tkinter as tk
    import subprocess
    
    top = tk.Tk()
    
    proc = None
    
    def turnOn():
        global proc
        if proc is None:
            print('Starting ping')
            proc = subprocess.Popen(["ping", "example.com"])
    
    def turnOff():
        global proc
        if proc is not None:
            print('Stopping ping')
            proc.terminate()
            proc = None
    
    on = tk.Button(top, text = "on", command = turnOn)
    off = tk.Button(top, text = "off", command = turnOff)
    
    on.grid()
    off.grid()
    
    top.mainloop()
    

    The if proc is None: line prevents the ping command from being re-launched if it's already running.