【问题标题】:How to run a single python function in parallel multiple times如何多次并行运行单个python函数
【发布时间】:2020-07-27 06:27:17
【问题描述】:

我有一个 python 函数,我想并行运行 100 次。这样做的代码是什么

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


options = Options()
options.headless = True
options.add_experimental_option("excludeSwitches", ['enable-automation']);
options.add_argument('--user-agent="Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 640 XL LTE) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Mobile Safari/537.36 Edge/12.10166"')
CHROMEDRIVER_PATH = 'c:\webdrivers\chromedriver.exe'
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=options)
def true():
    driver.get('https://youtu.be/Uhr5J5Sj-fU')
    driver.find_element_by_xpath('//*[@id="movie_player"]/div[2]/button/div').click()
    time.sleep(12*60+30)
    driver.quit()

【问题讨论】:

  • 您希望代码的哪一部分并行运行 100 次? multiprocessing 模块可能会引起您的兴趣。
  • true() 函数
  • 您还介意发布您迄今为止尝试并行运行代码的内容吗?

标签: python multithreading selenium selenium-webdriver python-multiprocessing


【解决方案1】:

使用python的线程模块 这可能对你有帮助

import threading
def hi():
    print('hi')
for i in range(0,100):
    t= threading.Thread(target=hi)
    t.start()

【讨论】:

  • 请注意,由于 CPython 实现中的全局解释器锁,线程模块可能无法提供真正的并行性。
  • 布鲁赫对我来说是希腊语
  • @KeshavReddy--解释更详细here,但基本上意味着多线程不会加速CPU密集型操作。
  • 不,这根本不是密集的。我愿意并行运行该函数 10 次,并且使用的 CPU 不到 20%
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多