【发布时间】:2021-07-04 16:19:00
【问题描述】:
我的问题是我有一个需要从 python 程序 UI 串行执行的 shell 命令列表。 shell 命令可能需要 10 秒到 10 分钟才能完成。我希望它们在后台运行而不阻塞主 UI/线程,所以我继续使用 python 程序。我尝试了以下方法来运行许多 shell 命令。
command_list = list()
for i in command_list:
os.system("Running command: ", i)
os.system()会一一执行命令列表,但是会阻塞主线程
同样适用于subprocess.run() 和subprocess.call()
subprocess.Popen() 不会阻塞主线程,而是会并行运行所有的 shell 命令,这是不可取的。
过去几天我尝试在 python discord 中搜索和询问,但无法找到解决问题的方法。
编辑: 假设我有这个 GUI 脚本,只是一个带有两个 QPushButton(“开始”、“停止”)的 QMainWindow。 “开始”将运行一个 shell 命令列表。 "Stop" 将停止 shell 命令的执行。
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_()
上面的代码会同时运行列表中的所有命令。
所以我尝试将 sleep() 放在 Popen 之间,但它也会冻结主 UI,并且无法单击“停止”按钮。
这是我最初的问题,即如何按顺序运行 shell 命令而不冻结主 UI/线程。谢谢你的时间。
【问题讨论】:
-
这能回答你的问题吗? PyQt5 and subprocess.Popen(...)
标签: python-3.x subprocess