My problem is that I have a list of shell commands that need to be executed serially from a python program UI. The shell commands can require anywhere from 10 seconds to 10 minutes to finish. And I want them run in the background without blocking the main UI/thread so I continue to use the python program. I have tried the following to run a number of shell commands.
command_list = list()
for i in command_list:
os.system("Running command: ", i)
os.system()
will execute the command list one by one, but will block the main thread
The same apply for subprocess.run()
andsubprocess.call()
subprocess.Popen()
will not block the main thread but will run all the shell commands in parallel which is not desirable.
I have tried googling and asking in python discord for the past few days but haven't been able find a solution to my problem.
Edit: Supposedly I have this GUI script, just a QMainWindow with two QPushButton ("Start", "Stop"). "Start" will run a list of shell commands. "Stop" will stop the execution of the shell commands.
class Window(qt.QMainWindow):
def __init__(self):
super().__init__()
central_widget = qt.QWidget()
central_widget.setLayout(qt.QHBoxLayout())
self.setCentralWidget(central_widget)
centra_widget.layout().addWidget(qt.QPushButton("Start", clicked = self.run_command))
centra_widget.layout().addWidget(qt.QPushButton("Stop", clicked = self.stop_command))
def run_command(self):
for cmd in cmd_list:
subprocess.Popen("Run command", cmd)
def stop_command(self):
# Do something to stop the shell commands
app = qt.QApplication([])
main_window = Window()
main_window.show()
app.exec_()
The code above will run every commands in the list at the same time.
So i tried putting sleep() between the Popen but it will also freeze the main UI and the "Stop" button cannot be clicked.
That was my original question as how to run shell commands in order and not freeze the main UI/thread. Thanks for you time.