代码:
`import os
import re
import time

from appium import webdriver

from iOSTest.AppiumBase.PhoneType import phone_type

def stop_appium(post_num):
'''关闭 appium 服务'''
p = os.popen(f'lsof -i tcp:{post_num}')
p0 = p.read()
if p0.strip() != '':
p1 = int(p0.split('\n')[1].split()[1]) # 获取进程号
os.popen(f'kill {p1}') # 结束进程
print('appium server 已结束')

def start_appium(post_num):
'''开启 appium 服务'''
stop_appium(post_num) # 先判断端口是否被占用,如果被占用则关闭该端口号
# 根据系统,启动对应的服务
cmd_dict = {
'MAC': f'appium -a 127.0.0.1 -p {post_num} --log xxx.log --local-timezone & '
}
os.system(cmd_dict['MAC'])
time.sleep(3) # 等待启动完成
print('appium 启动成功')

def get_device():
value = os.popen("adb devices")

device = []

for v in value.readlines():
android = {}
s_value = str(v).replace("\n", "").replace("\t", "")
if s_value.rfind('device') != -1 and (not s_value.startswith("List")) and s_value != "":
android['platformName'] = 'Android'
android['deviceName'] = s_value[:s_value.find('device')].strip()
# deviceAndroidVersion = list(os.popen('adb shell getprop ro.build.version.release').readlines())
# android['platformVersion'] = re.findall(r'\w*\b', deviceAndroidVersion[0])[0]
android['appPackage'] = 'packagename'
android['appActivity'] = '.activity.LaunchActivity'
android['automationName'] = 'uiautomator2'
android['noReset'] = True
device.append(android)

value = os.popen("instruments -s devices")

for v in value.readlines():
iOS = {}

s_value = str(v).replace("\n", "").replace("\t", "").replace(" ", "")

if v.rfind('Simulator') != -1:
continue
if v.rfind("(") == -1:
continue

iOS['platformName'] = 'iOS'
iOS['platformVersion'] = re.compile(r'((.))').findall(s_value)[0]
iOS['udid'] = re.compile(r'[(.
?)]').findall(s_value)[0]
udid = iOS['udid']
name = list(os.popen('ideviceinfo -u "{}" -k ProductType'.format(udid)).readlines())
devicename = "/n".join(name).strip('\n')
iOS['deviceName'] = phone_type(devicename)
iOS['bundleId'] = 'pakagename'
iOS['xcodeOrgId'] = '2DJ994BZUB'
iOS['xcodeSigningId'] = 'iPhone Developer'
iOS['noReset'] = True

device.append(iOS)

return device

def run(port, capabilities):
driver = webdriver.Remote('http://localhost:/wd/hub'.format(port){}, capabilities)
return driver

count = len(get_device())
port = 4723
for i in range(count):
stop_appium(port)
start_appium(port)
print(get_device()[i])
driver = run(port, get_device()[i])
time.sleep(3)
driver.launch_app()
port = port + 2
driver.quit()`
代码逻辑:端口号从 4723 开始,把获取的设备信息存到一个 device 列表,遍历列表,启动不同端口的 appium 服务。
结果:连接了两个手机,只在一个手机上启动了 2 次,另外一个手机无反应,求大神看一哈


↙↙↙阅读原文可查看相关链接,并与作者交流