osx: 10.15
python: 3.6.5
airetest ios需要执行两部shell命令,且需要一直执行,借用python来后台执行
之前的功能是网上转载的,由于业务需求,读了下subprocess源码,新增了个kill功能,实现终止后台运行的shell
#coding:utf-8
import subprocess, time
class Shell(object):
def __init__(self, cmd):
self.cmd = cmd
self.ret_code = None
self.ret_info = None
self.err_info = None
def run_background(self):
self._process = subprocess.Popen(self.cmd, shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def get_status(self):
retcode = self._process.poll()
if retcode == None:
status = "RUNNING"
else:
status = "FINISHED"
return status
def print_output(self):
for _ in range(6):
line = self._process.stdout.readline() # 这儿会阻塞
if line:
print ("output:",line)
else: # 只有子进程结束后, 才会有readline返回""的情况
print ("no ouput yet")
def kill(self):
self._process.kill()
shells = '/usr/bin/xcodebuild -project WebDriverAgent.xcodeproj -scheme WebDriverAgentRunner -destination id=`system_profiler SPUSBDataType | grep "Serial Number:.*" | sed s#".*Serial Number: "##` test'
keepprinting1 = Shell(shells)
keepprinting1.run_background()
keepprinting1.print_output()
keepprinting2 = Shell("iproxy 8100 8100") # keepprint will print out one line every 2 seconds
keepprinting2.run_background()
keepprinting2.print_output()
count = 0
while True:
print("====running===="+str(count))
count+=1
print(keepprinting1.get_status())
print(keepprinting2.get_status())
time.sleep(2)
if count == 7:
keepprinting1.kill()#终止后台线程1