嘿,大家都相信你很好,我目前正在嘗試讓每個行程(執行緒)讀取不同的 txt 檔案或從一個文本檔案中讀取,并為每個行程分配一定數量。
示例:如果 txt 檔案包含20 個用戶名,則將一條訊息處理給文本檔案中指定的前10 個用戶,并將兩條訊息處理給文本檔案中指定的其他10 個用戶。
問題:假設檔案有 20 行,我將如何讀取文本檔案中的 10 行、洗掉 10 行并在創建每個行程時讀取接下來的 10 行?
讀取指定數量
with open("test.txt", "r") as fp:
for linenr, line in enumerate(fp):
if linenr > 9:
break
elif linenr >= 0:
print(line)
洗掉指定數量
with open("test.txt", 'r ') as fp:
# read an store all lines into list
lines = fp.readlines()
# move file pointer to the beginning of a file
fp.seek(0)
# truncate the file
fp.truncate()
# start writing lines except the first line
# lines[1:] from line 2 to last line
fp.writelines(lines[10:])
代碼:
import time
from selenium import webdriver
import threading
import json
def test_instance(data):
Options = webdriver.ChromeOptions()
mobile_emulation = {"userAgent": "Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/101.0.4951.64 Mobile Safari/535.19"}
Options.add_experimental_option("mobileEmulation", mobile_emulation)
Options.add_argument("--log-level=3")
bot = webdriver.Chrome(options=Options, executable_path="chromedriver.exe")
bot.set_window_size(500, 768)
bot.get("https://www.instagram.com/")
time.sleep(10)
# Login section==========================
print('Logging in...')
bot.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div/div/div/div[3]/button[1]').click()
time.sleep(5)
username_field = bot.find_element_by_xpath('//*[@id="loginForm"]/div[1]/div[3]/div/label/input')
username_field.send_keys(data['username'])
time.sleep(5)
password_field = bot.find_element_by_xpath('//*[@id="loginForm"]/div[1]/div[4]/div/label/input')
password_field.send_keys(data['password'])
time.sleep(5)
bot.find_element_by_xpath('//*[@id="loginForm"]/div[1]/div[6]/button').click()
time.sleep(6)
bot.quit()
f = open('accounts.json',)
data = json.load(f)
f.close()
process_count = 2 # number of tests to run (each test open a separate browser)
thread_list = []
# Start test
for i in range(process_count):
t = threading.Thread(name=f'Test {i}', target=test_instance, args=[data[i]])
t.start()
time.sleep(1)
print(t.name ' started')
thread_list.append(t)
# Wait for all threads to complete
for thread in thread_list:
thread.join()
print('Test completed')
uj5u.com熱心網友回復:
嘗試通過不同的執行緒同時讀取和寫入同一個檔案通常是一個非常糟糕的主意,特別是如果您也在尋找和截斷檔案。除非您使用 aLock來序列化訪問,否則您無法確定以什么順序讀取/寫入哪些資料。
為了簡單起見,我建議讓主程式將輸入檔案讀入串列。給每個thead 串列中的一部分以采取行動。
讀取用戶串列的示例:
# Read file into list:
with open("users.txt") as uf:
users = [ln.strip() for ln in tf if ln[0] not in '\r\n']
讓我們分解這段代碼(它被稱為串列理解):
for ln in tf
遍歷檔案中的行。
if ln[0] not in '\r\n'
這會跳過空行。
ln.strip()
這將洗掉例如換行符和回車符。
請注意,-statement完成后,是一個關閉的檔案,因此您無法再從中讀取。withuf
為要迭代的執行緒創建對
假設numusers(即len(users))是 34。
numusers = 34
然后我們可以創建一個這樣的對串列:
im = [n for n in range(numusers 1) if n % 10 == 0 or n == numusers]
這將產生串列[0, 10, 20, 30, 34]
現在創建對:
pairs = list(zip(im[:-1], im[1:]))
然后pairs就會[(0, 10), (10, 20), (20, 30), (30, 34)]
使用 ThreadPoolExecutor
然后,您可以撰寫一個將 2 元組(0, 10)作為引數的函式,并為每個用戶執行一些操作。
import concurrent.futures as cf
def target(pair):
first, last = pair
for user in users[first, last]:
# do the whole login thing
# You should probably at least return a success or error code.
return f"users {users[first]} to {users[last-1]} processed"
with cf.ThreadPoolExecutor(max_workers=2) as exec:
results = exec.map(target, pairs)
我建議讓每個執行緒將它想要寫入的資料放在一個串列中。當所有作業執行緒完成后,連接串列,然后將它們從主執行緒寫入輸出檔案。
或者,您可以從每個執行緒寫入,但您必須使用 a 保護檔案訪問Lock,因此您不會有多個行程嘗試一次寫入同一個檔案。
要記住的另一件事是,這chrome不是一個輕量級的軟體!同時運行太多實體可能會使您的 PC 過載或使您的網路連接飽和。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/485014.html
上一篇:執行器服務回傳不正確的回應
