def send_cmd(cmd, encoding='utf-8'): ''' cmd发送命令 :param cmd:命令 :param encoding: 编码方式,默认utf-8,出现乱码用gbk :return: ''' res = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding=encoding) com = res.communicate() value = com[0] res.terminate() return value def start_appium(port,name): bp = int(port) +1 kill_appium_server(port=port) kill_appium_server(port=bp) appium_log = os.path.join(DirPath.Logs, 'Appium_' + name + '.log') # 后台执行 cmd = "start appium -p " + str(port) + " -bp " + str( bp) + " -g " + appium_log + " --session-override -a 127.0.0.1 --command-timeout 300" log.info(cmd) os.popen(cmd) time.sleep(10) def kill_appium_server(port): try: # 查找对应端口的pid cmd_find = 'netstat -aon | findstr %s' % port text = send_cmd(cmd_find, encoding="gbk") if text != '': res = text.split(" ") for i in res: if "LISTENING" in i: pid = (i.split()[-1]).strip() # 执行被占用端口的pid cmd = 'taskkill /f /pid %s' % pid res = send_cmd(cmd, encoding="gbk") log.debug(str(res).strip()) if ("成功" in res) or ("SUCCESS".lower() in res.lower()): log.debug("port %s appium server close" %str(port)) else: return except: return
appium做安卓自动化的时候,需要用代码启动和关闭appium服务;
思路:找到服务对应的端口的进程,杀死进程;