Python 多线程操作多设备启动应用

xiaoxiao · August 07, 2019 · Last by xiaoxiao replied at August 08, 2019 · 609 hits

通过启用多线程传入不同设备参数进行操控,代码如下:

# -*- coding: utf-8 -*-
# @file: thread_multiple_devices.py
# @author: xiaoxiao
# @date : 2019/8/6

import threading
import subprocess
import time


class ThreadMultipleDevices():

def __init__(self, package_name):
self.package_name = package_name

# 启动app应用
def app_start(self, launch_activity, device_id=''):
if device_id != '':
cmd_start = "adb -s %s shell am start -n %s" % (device_id, self.package_name + "/" + launch_activity)
else:
cmd_start = "adb shell am start -n %s" % (self.package_name + "/" + launch_activity)
subprocess.Popen(cmd_start, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
print('Running device:' + threading.current_thread().name + ', app start success:'+ str(cmd_start))
time.sleep(5)

def test_meizu16_app_start(self):
self.app_start('com.yyy', devices[0])

def test_vivo_X9_app_start(self):
self.app_start('com.yyy', devices[1])


devices = ['882QADT9UWTBW', 'e9d3a867']
thread_mulitple_devices = ThreadMultipleDevices('com.xxx')
t1 = threading.Thread(target=thread_mulitple_devices.test_meizu16_app_start, name='meizu16')
t2 = threading.Thread(target=thread_mulitple_devices.test_vivo_X9_app_start, name='vivo X9')
t1.start()
t2.start()
print('======= end =========')

执行结果:

======= end =========
Running device:meizu16, app start success:adb -s e9d3a867 shell am start -n com.xxx/com.yyy
Running device:vivo X9, app start success:adb -s 882QADT9UWTBW shell am start -n com.xxx/com.yyy

共收到 5 条回复 时间 点赞

如果需要带参传入test_meizu16_app_start或test_vivo_X9_app_start,则用args带入即可

t1 = threading.Thread(target=thread_mulitple_devices.test_meizu16_app_start, args=('882QADT9UWTBW',), name='meizu16')
t2 = threading.Thread(target=thread_mulitple_devices.test_vivo_X9_app_start, args=('e9d3a867',), name='vivo X9')

执行一半cmd_start就去执行另外一个cmd_start

3Floor has been deleted
hellohell 回复

不是,多线程的执行不是我们想的那样等一个执行完毕才执行另一个,启动执行的时间是随机的,但从感官上基本是同时执行😁

hellohell 回复

看了下,不知道哪个地方需要注释呢?这个不涉及到主线程和子线程的问题,所以不需要stop子线程啥的,这个代码两个线程执行完毕会自动停掉了

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up