我有一些问题,因为我是 Python 和 Pyside 的新手。
我有N个进程同时运行。
由于这些进程需要一些时间才能完成其工作,因此最终用户可能想要取消特定进程。因此,我需要一种方法来了解进程的 ID,以便将此功能添加到程序中。
有一个answer https://stackoverflow.com/a/15875187/3152155在 Stackoverflow 中,这正是我正在做的事情。
这是代码:
#!/usr/bin/env python3
import multiprocessing, multiprocessing.pool, time, random, sys
from PySide.QtCore import *
from PySide.QtGui import *
def compute(num_row):
print("worker started at %d" % num_row)
random_number = random.randint(1, 10)
for second in range(random_number):
progress = float(second) / float(random_number) * 100
compute.queue.put((num_row, progress,))
time.sleep(1)
compute.queue.put((num_row, 100))
def pool_init(queue):
# see https://stackoverflow.com/a/3843313/852994
compute.queue = queue
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.toolBar = self.addToolBar("Toolbar")
self.toolBar.addAction(QAction('Add Task', self, triggered=self.addTask))
self.table = QTableWidget()
self.table.verticalHeader().hide()
self.table.setColumnCount(2)
self.setCentralWidget(self.table)
# Pool of Background Processes
self.queue = multiprocessing.Queue()
self.pool = multiprocessing.Pool(processes=4, initializer=pool_init, initargs=(self.queue,))
# Check for progress periodically
self.timer = QTimer()
self.timer.timeout.connect(self.updateProgress)
self.timer.start(2000)
def addTask(self):
num_row = self.table.rowCount()
self.pool.apply_async(func=compute, args=(num_row,))
label = QLabel("Queued")
bar = QProgressBar()
bar.setValue(0)
self.table.setRowCount(num_row + 1)
self.table.setCellWidget(num_row, 0, label)
self.table.setCellWidget(num_row, 1, bar)
def updateProgress(self):
if self.queue.empty(): return
num_row, progress = self.queue.get() # unpack
print("received progress of %s at %s" % (progress, num_row))
label = self.table.cellWidget(num_row, 0)
bar = self.table.cellWidget(num_row, 1)
bar.setValue(progress)
if progress == 100:
label.setText('Finished')
elif label.text() == 'Queued':
label.setText('Downloading')
self.updateProgress() # recursion
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
我添加了一个“停止”按钮,并且我知道如何获取表中所选的行,但我不知道如何获取所选行的进程ID以终止。
update 1 :
为了让这更容易我可以改变
multiprocessing.Pool(processes=4, initializer=pool_init, initargs=(self.queue,))
to
multiprocessing.Pool(processes=1, initializer=pool_init, initargs=(self.queue,))
这样所有进程都必须等到进程完成
现在我们有一个进程正在运行,其他进程正在队列中,我如何才能获取该正在运行的进程的进程ID?