如何调整我的 Python 子进程代码,以便 python 脚本 运行 并行?

How can I adjust my Python subprocess code so that the python scripts run in parallel?

我有两个 selenium python 代码。我正在 运行 使用子进程脚本将它们连接起来:

import subprocess
subprocess.run("python script1.py & python script2.py", cwd=r'C:\Users\David\Desktop\Selenium', shell=True)

当我运行他们时,他们不是并行运行而是顺序运行。有谁知道我是怎么做的可以修改此脚本,以便它们 运行 同时(并行)吗?

这是脚本 1 和 2 的代码:

script1.py

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options=Options()

driver=webdriver.Chrome(options=options)

params={'behavior':'allow','downloadPath':r'C:\Users\David\Downloads'}
driver.execute_cdp_cmd('Page.setDownloadBehavior',params)

driver.get("https://data.gov.uk/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/main/div[2]/form/div/div/input"))).send_keys("Forestry Statistics 2018: Recreation")

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/main/div[2]/form/div/div/div/button"))).click()


WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/form/main/div/div[2]/div[2]/div[2]/h2/a"))).click()

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/main/div/div/div/section/table/tbody/tr[2]/td[1]/a"))).click()

script2.py

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options=Options()

driver=webdriver.Chrome(options=options)

params={'behavior':'allow','downloadPath':r'C:\Users\David\Downloads'}
driver.execute_cdp_cmd('Page.setDownloadBehavior',params)

driver.get("https://data.gov.uk/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/main/div[2]/form/div/div/input"))).send_keys("NI 179 - Value for money")

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/main/div[2]/form/div/div/div/button"))).click()


WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/form/main/div/div[2]/div[2]/div[2]/h2/a"))).click()

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/main/div/div/div/section/table/tbody/tr/td[1]/a"))).click()

我不确定 subprocess.run 到底是如何工作的,但我已经尝试过 subprocess.Popen,它运行良好。

试试这个:

import subprocess
firstScript = subprocess.Popen(["python", "C:/Users/David/Desktop/Selenium/script1.py"], shell=True)
secondScript = subprocess.Popen(["python", "C:/Users/David/Desktop/Selenium/script2.py"], shell=True)

firstScript.wait()
secondScript.wait()