Asyncio event loop per python process (aioprocessi

2020-05-24 09:37发布

问题:

I have two processes; a main process and a subprocess. The main process is running an asyncio event loop, and starts the subprocess. I want to start another asyncio event loop in the subprocess. I'm using the aioprocessing module to launch the subprocess.

The subprocess function is:

def subprocess_code():
     loop = asyncio.get_event_loop()
     @asyncio.coroutine
     def f():
        for i in range(10):
            print(i)
            yield from asyncio.sleep(1)
     loop.run_until_complete(f())

But I get an error:

    loop.run_until_complete(f())
  File "/usr/lib/python3.4/asyncio/base_events.py", line 271, in run_until_complete
    self.run_forever()
  File "/usr/lib/python3.4/asyncio/base_events.py", line 239, in run_forever
    raise RuntimeError('Event loop is running.')
RuntimeError: Event loop is running.

Is it possible to start a new, or restart the existing, asyncio event loop in the subprocess? If so, how?

回答1:

Sorry for disturb! I found a solution!

policy = asyncio.get_event_loop_policy()
policy.set_event_loop(policy.new_event_loop())
loop = asyncio.get_event_loop()

put this code to start new asycnio event loop inside of subprocess started from process with asyncio event loop