I am creating an automanipulator on android emulator and get data from csv file for text input. I want to run multiple emulator threads and import data at the same time, repeating the whole process until all the data in the file is used up.
import subprocess
import uiautomator2 as u2
import sys
import threading
from time import sleep
import csv
def start_memu_emulator(instance_id):
# code
def sort_windows():
# code
def start_app(emulator):
# code
def begin(emulator):
# Input FirstName
emulator.send_keys(first_name)
emulator.implicitly_wait(10.0)
emulator(resourceId="lastName").click()
# Input LastName
emulator.send_keys(last_name)
emulator.implicitly_wait(10.0)
emulator(text="Next").click()
sleep(10)
def stop_memu_emulator():
# code
def run_functions(emulator):
sort_windows()
start_app(emulator)
begin(emulator)
stop_memu_emulator()
with open('name.csv', 'r') as file:
# Create a CSV reader object
reader = csv.DictReader(file)
# Iterate over the rows of the CSV file
for row in reader:
first_name = row["Name"]
last_name = row["Pass"]
# Ask the user for the number of emulator threads to run
num_threads = int(input("Enter the number of emulator threads to run: "))
# Start the desired number of MEmu emulator instances
for i in range(num_threads):
instance_id = i
start_memu_emulator(instance_id)
# Run the adb devices command and capture the output
output = subprocess.run(['adb', 'devices'], capture_output=True)
# Split the output into lines and remove the first line (which is a header)
lines = output.stdout.decode().strip().split('\n')[1:]
# Parse the lines into columns using the csv.reader function
reader = csv.reader(lines, delimiter='\t', quoting=csv.QUOTE_NONE)
# Extract the serial numbers from the first column of each row
serials = [row[0].split('\t')[0] for row in reader]
print('Devices series:', serials)
# Connect to each emulator instance using the serial number
emulators = []
for serial in serials[:num_threads]:
emulator = u2.connect(serial)
emulators.append(emulator)
# Use threading to run the start_gmail function on each emulator
threads = []
for emulator in emulators:
thread = threading.Thread(target=run_functions, args=(emulator,))
threads.append(thread)
thread.start()
# Wait for all threads to finish
for thread in threads:
thread.join()
How can multiple threads get data on the same file without overlapping with other threads? Can someone help me? Thanks a lot!
CodePudding user response:
You have a CSV and you want discrete threads to process each record/row in the CSV file.
Let's say we have this CSV file:
A,B,C
1,2,3
4,5,6
...then...
from csv import DictReader
from concurrent.futures import ThreadPoolExecutor
def process(line):
print(line)
with open('foo.csv') as data:
with ThreadPoolExecutor() as tpe:
tpe.map(process, DictReader(data))
Output:
{'A': '1', 'B': '2', 'C': '3'}
{'A': '4', 'B': '5', 'C': '6'}