Python多进程在终止后多次运行同一进程 - AssertionError: 不能多次启动进程

0 投票
1 回答
27 浏览
提问于 2025-04-14 15:27

我刚接触Python的多进程编程,想请教一下怎么在一个进程结束后再连续运行它多次。在下面的例子中,我需要每隔10秒重新运行一个比较长的任务。用普通的方式运行没问题,但我在用Python的多进程时遇到了困难。

因为我无法通过Python的多进程让它正常运行,所以想请教一下大家。

非常感谢!

克里斯蒂安

没有使用多进程的代码
#!/usr/bin/python3
import time
import multiprocessing

def task(i):
    print("task : ",i)

if __name__ == '__main__':
    i=0
    old_run = 0.0
    while True:
       now=time.time()
       if (now - old_run >10):
         old_run=now
         task(i)                  <<< goal is to get this done via multiprocess
       print("main:", i)
       i=i+1
       time.sleep (1)

我下面的代码没有成功,最后出现了“AssertionError: cannot start a process twice”的错误。

使用多进程的代码但不成功
#!/usr/bin/python3
import time
import multiprocessing

def task(i: int):
    print("task : ",i)

if __name__ == '__main__':
    processes = []
    i=0
    old_run = 0.0
    while True:
       now=time.time()
       if (now - old_run >10):
         old_run=now
         processes.append(multiprocessing.Process(target=task,args=(i,)))
         for process in processes:
            process.start()
            process.join()
            process.terminate()
       print("main:", i)
       i=i+1
       time.sleep (1)

失败的多进程代码片段的输出结果

`behn@rpi2:~ $ ./multi.py

task :  0
main: 0
main: 1
main: 2
main: 3
main: 4
main: 5
main: 6
main: 7
main: 8
main: 9
Traceback (most recent call last):
  File "/home/behn/./multi.py", line 22, in <module>
    process.start()
  File "/usr/lib/python3.11/multiprocessing/process.py", line 115, in start
    assert self._popen is None, 'cannot start a process twice'
           ^^^^^^^^^^^^^^^^^^^
AssertionError: cannot start a process twice`

1 个回答

0

我自己来回答一下..

简化后的代码:

q_do_auth_and_query = multiprocessing.Queue()
while True:
   now=time.time()
   if (now - last_sems_run > 15):
      last_sems_run=now
      mp_do_auth_and_query = multiprocessing.Process(target=sems.do_auth_and_query,args=(token,q_do_auth_and_query))
      mp_do_auth_and_query.start()
   while (not q_do_auth_and_query.empty()):
      q=q_do_auth_and_query.get()

撰写回答