如何使用asyncio减少ProcessPoolExecutor的cpu使用率?

时间:2019-04-07 15:29:07

标签: python asynchronous python-asyncio

我像下面一样使用ProcessPoolExecutor

def main(argv):
    set_argv(argv)
    # running code. Loop button click, enter text, submit.
if __name__ == '__main__':
    executer = ProcessPoolExecutor(max_workers=9)
    argvs = ["D", "E", "F", "G", "H", "I", "J", "K", "L"]
    for argv in argvs:
        executer.submit(main,argv)

但是此代码使用了100%的CPU,每个进程花费的时间是完成一个进程的两倍。

所以我想使用asyncio来减少CPU使用率。但是下面的代码会产生错误。

async def async_set():
    coroutines = []
    argvs = ["D", "E", "F", "G", "H", "I", "J", "K", "L"]
    fts = [loop.run_in_executor(main(m)) for m in argvs]
    for f in asyncio.as_completed(fts, loop=loop):
        await f

async def main(argv):
    set_argv(argv)
    # running code. Loop button click, enter text, submit.

loop = asyncio.get_event_loop()
    loop.run_until_complete(async_set())
    loop.close()

错误是:

 fts = [loop.run_in_executor(main(m)) for m in argvs]
TypeError: run_in_executor() missing 1 required positional argument: 'func'

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

在更改fts之后,如下所示

fts = [loop.run_in_executor(None, main, m) for m in argvs]

出现错误,但只有1个进程正常运行

Traceback (most recent call last):
  File "C:/Users/admin/Desktop/test/Version/test.py", line 593, in <module>
    loop.run_until_complete(async_set())
  File "C:\Python\Python37\lib\asyncio\base_events.py", line 584, in run_until_complete
    return future.result()
  File "C:/Users/admin/Desktop/test/Version/test.py", line 60, in async_set
    await f
  File "C:\Python\Python37\lib\asyncio\tasks.py", line 533, in _wait_for_one
    return f.result()  # May raise f.exception().
  File "C:\Python\Python37\lib\concurrent\futures\thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "C:/Users/admin/Desktop/test/Version/test.py", line 67, in main
    set_login(ID, PW)
  File "C:/Users/admin/Desktop/test/Version/test.py", line 188, in set_login
    driver.find_element_by_xpath('//*[@id="header"]/div/div[1]/ul[2]/li[1]/a').click()
  File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\webelement.py", line 633, in _execute
    return self._parent.execute(command, params)
  File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=73.0.3683.86)
  (Driver info: chromedriver=73.0.3683.68 (47787ec04b6e38e22703e856e101e840b65afe72),platform=Windows NT 10.0.17763 x86_64)

1 个答案:

答案 0 :(得分:0)

我不知道它模仿您的过程的程度如何,但是运行:

import asyncio
import concurrent.futures

def main(argv):
    t = random.choice([.02,.1,.5,.3,1.0,2.0,3.0,5.,6.,7.,8.,9.])
    time.sleep(t)
    return (t, argv * 2)

async def async_set():
    loop = asyncio.get_event_loop()
##    coroutines = []
    argvs = ["D", "E", "F", "G", "H", "I", "J", "K", "L"]
    with concurrent.futures.ProcessPoolExecutor() as pool:
        stuff = [loop.run_in_executor(pool,main,arg) for arg in argvs]
        for fut in asyncio.as_completed(stuff):
            print(await fut)

if __name__ == '__main__':

    loop = asyncio.get_event_loop()
    loop.run_until_complete(async_set())
    loop.close()

>>>
(0.5, 'EE')
(0.5, 'DD')
(0.5, 'FF')
(7.0, 'HH')
(8.0, 'II')
(0.1, 'LL')
(9.0, 'GG')
(9.0, 'JJ')
(7.0, 'KK')
>>>