class Port: def __init__(self): self.dos_cmd = DosCmd() # 判断端口是否被占用 def port_is_use(self, port_num): command = 'netstat -ano | findstr ' + str(port_num) result = self.dos_cmd.execute_result_cmd(command) if len(result) > 0: flag = True else: flag = False return flag # 生成可用的端口列表,是为有几个手机设备做准备 def create_use_port(self, start_port, devices_list): # 放可用端口的集合,有几个设备就有几个端口 port_list = [] if len(devices_list) > 0: while len(port_list) != len(devices_list): # 判断传进来的端口是否被占用,如果没有被占用,那就添加到可用端口的列表集合中 if self.port_is_use(start_port) is not True: port_list.append(start_port) # 因为有很多个设备,那就要生成很多的端口,当添加完一个端口到可用端口列表中后,下一个端口就要加1 start_port = start_port + 1 return port_list else: return None
class Server: def __init__(self): self.dos_cmd = DosCmd() self.port = Port() self.write_yaml = WriteDeviceYaml() self.get_devices_num = self.get_devices_list() # 获取所有设备的列表 def get_devices_list(self): device_list = [] devices = self.dos_cmd.execute_result_cmd("adb devices") if len(devices) >= 2: for device_name in devices: if "List" in device_name: continue flag = device_name.split("\t")[1] if flag == "device": device_list.append(device_name.split("\t")[0]) return device_list else: return None # 创建可用的端口 def create_use_port(self, start_port): return self.port.create_use_port(start_port, self.get_devices_list()) # 生成命令 def create_command_list(self, i): # appium -p 4700 -bp 4900 -U 127.0.0.1:62001 command_list = [] appium_list = self.create_use_port(4700) bootstrap_list = self.create_use_port(4900) devices = self.get_devices_list() command = " appium -p " + str(appium_list[i]) + " -bp " + str( bootstrap_list[i] ) + " -U " + str( devices[i] ) + " --no-reset --session-override --log E:/pycharmProject/appium/appiumProject/log/appium_log" + str( i) + ".log" command_list.append(command) # 把设备的端口,bootstrap端口和设备名称写入yaml文件中,方便在初始化driver时候使用 self.write_yaml.write_value(i, str(appium_list[i]), str(bootstrap_list[i]), str(devices[i])) return command_list # 启动服务 def start_server(self, i): start_list = self.create_command_list(i) print(start_list) # 因为是在多线程中,每次启动,只有第一个命令 self.dos_cmd.execute_cmd(start_list[0]) # 关闭服务 def kill_server(self): node_list = self.dos_cmd.execute_result_cmd( 'tasklist | find "node.exe"') # print(node_list) if len(node_list) > 0: self.dos_cmd.execute_cmd('taskkill -F -PID node.exe') # 启动服务的主入口,几个设备就启动几个服务 def main(self): # 启动程序的时候,先把已开启的node.exe程序杀死 self.kill_server() # 再把数据写入yaml文件前先把yaml文件中数据清空 self.write_yaml.clear_value() for i in range(len(self.get_devices_num)): appium_thread = threading.Thread(target=self.start_server, args=(i, )) appium_thread.start() # 因为是多个机器,这个地方一定要等待一下,让所有的设备都能运行起来 sleep(5)