Python无法从外部停止协同程序中的while循环

2024-04-25 18:48:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从外部动态控制爬行器,如添加或停止,如何修复它

以及过程中定义self.\u loop=asyncio.get\u event\u loop()启动后提升:

File "Python38\lib\multiprocessing\spawn.py", line 102, in spawn_main
    source_process = _winapi.OpenProcess(
OSError: [WinError 87] The parameter is incorrect

为什么?

我的平台是Windows

import asyncio
from multiprocessing import Process


class Spider(Process):
    def __init__(self):
        super().__init__()
        self._stopped = False

    def run(self):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.fetching())

    async def fetching(self):
        while True:
            if self._stopped:  # not update variable
                await asyncio.sleep(1)
                continue
            print("fetching...")
            await asyncio.sleep(1)

    def stop(self):
        self._stopped = True
        print('stop', self._stopped)


if __name__ == "__main__":
    import time

    s = Spider()
    s.start()
    time.sleep(2)
    s.stop()

输出为:

fetching...
fetching...
stop True
fetching...
fetching...

Tags: importselfloopeventasynciotruegetmain
1条回答
网友
1楼 · 发布于 2024-04-25 18:48:57

您应该在这两个进程(主进程和您创建的进程)之间使用共享内存。考虑使用{a1}

修复了您的代码:

import asyncio
from ctypes import c_bool
from multiprocessing import Process, Value


class Spider(Process):
    def __init__(self):
        super().__init__()
        self._stopped = Value(c_bool, False)  # <== here

    def run(self):
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self.fetching())

    async def fetching(self):
        while True:
            if self._stopped.value:  # <== here
                await asyncio.sleep(1)
                continue
            print("fetching...")
            await asyncio.sleep(1)

    def stop(self):
        self._stopped.value = True  # <== here
        print('stop', self._stopped)


if __name__ == "__main__":
    import time

    s = Spider()
    s.start()
    time.sleep(2)
    s.stop()

但是老实说,如果您得到的“stopped”值为True,那么您应该从循环中break,而不是永远继续它

相关问题 更多 >