前期使用时,手动在终端输入appium,可以启动服务
但为了更多的自动化范围,希望python能自动启动和关闭appium服务
Python执行cmd面板中命令行
import os
os.system("appium")
可以模拟执行命令行命令。但是缺点是:它是同步的,当命令行中的命令执行完成之后,才会接着往下执行。但是,我们使用appium需要的是开启一个进程后,可以继续执行我们的其他测试代码,当前方法不满足。
查进程号,杀掉进程的cmd命令
#Windows命令
netstat -ano | findstr 4723 # 根据进程使用的端口号,查找进程的进程号
taskkill -f -pid 22668 # 根据进程号,杀掉进程
#mac命令
lsof -i tcp:4723
kill 22668
Python使用subprocess 子进程的方式启动appium
import subprocess
import os, sys
import time
def stop_appium(port):
mac_cmd = f"lsof -i tcp:{port}"
win_cmd = f"netstat -ano | findstr {port}"
# 判断操作系统
os_platform = sys.platform
print('操作系统:', os_platform)
# #windows 系统
if os_platform == "win32":
win_p = subprocess.Popen(win_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in win_p.stdout.readlines():
if line:
line = line.decode('utf8')
if "LISTENING" in line:
win_pid = line.split("LISTENING")[1].strip()
os.system(f"taskkill -f -pid {win_pid}")
else:
# unix系统
p = subprocess.Popen(mac_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in p.stdout.readlines():
line = line.decode('utf8')
if "node" in line:
stdoutline = line.split(" ")
# print(stdoutline)
pid = stdoutline[4]
os.system(f"kill {pid}")
def start_appium(port):
"""
启动appium 服务
:param port: 服务的端口号
:return:
"""
stop_appium(port)
cmd = f"appium -p {port}"
logsdir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs")
appium_logs = os.path.join(logsdir, "appium-logs")
if not os.path.exists(appium_logs):
os.mkdir(appium_logs)
log_name = str(port) + '-' + time.strftime('%Y_%m_%d') + ".log"
appium_logs_dirName = os.path.join(appium_logs, log_name)
subprocess.Popen(cmd, shell=True, stdout=open(appium_logs_dirName, mode='a', encoding="utf8"),
stderr=subprocess.PIPE)
print(logsdir)
print(log_name)
print(appium_logs_dirName)
if __name__ == '__main__':
start_appium(4724)
stop_appium(4724) #这里不能使用默认的4723,不知道为什么