上两篇文章:
一个是当os.path.exists(path)的path中带有空格时的解决方案
一个是当路径中有空格时adb命令时会出错的解决方案,说到底其实本质是用adb的用法的了解.
但还有一种情况是,当文件中带有空格时也会出错?如要安装一个带有空格的apk怎么解决呢?、
以下是一个典型的场景:
In [72]: path = input('请将apk拖入此处:')
请将apk拖入此处:"C:\Users\xxxxx\Desktop\00test\com qiyi video.apk"
In [73]: path
Out[73]: '"C:\\Users\\xxxxx\\Desktop\\00test\\com qiyi video.apk"'
In [74]: path = path.replace('\"', '')
In [75]: path
Out[75]: 'C:\\Users\\xxxxx\\Desktop\\00test\\com qiyi video.apk'
In [76]: cmd = 'adb install -t ' + path
In [77]: cmd
Out[77]: 'adb install -t C:\\Users\\xxxxx\\Desktop\\00test\\com qiyi video.apk'
In [78]: subprocess.run(cmd, shell=True)
Failed to stat video.apk: No such file or directory
Out[78]: CompletedProcess(args='adb install -t C:\\Users\\xxxxx\\Desktop\\00test\\com qiyi video.apk', returncode=1)
同样的报错原因,带空格的filename被识别成了多个参数. 网上search了方法,要想能成功识别, 可以给这个file加上双引号"".
即将cmd变为:
'adb install -t C:\\Users\\xxxxx\\Desktop\\00test\\"com qiyi video.apk"'即可
所以可以在识别文件时先判断一下file是否带空格,带空格就给filename加上双引号就行了.
if filename.count(' ') != 0:
filename = '\"' + filename + '\"'
完整的实例如下:
def installapk():
try:
path = input('请将待安装apk或apk folder拖入Console中:').replace('\"', "")
if os.path.exists(path) is False:
print('文件路径不存在,请确认?!')
return
else:
# 如果拖入的是一个apk文件
if os.path.isfile(path) is True:
filepath, file = os.path.split(path)
if os.path.splitext(path)[1] != '.apk':
print('非apk文件,无法安装.')
return
os.chdir(filepath)
if file.count(' ') != 0:
file = '\"' + file + '\"'
cmdinstall = 'adb install -t ' + file
print(f'{getnowdatatime(2)} apk正在安装... ...')
startInstallTime = time.time()
if subprocess.run(cmdinstall).returncode == 0:
print('apk已安装成功!')
s_time = time.strftime('%y-%m-%d %H:%M:%S', time.localtime(startInstallTime))
print(f'{s_time}')
endInstallTime = time.time()
e_time = time.strftime('%y-%m-%d %H:%M:%S', time.localtime(endInstallTime))
print(f'{e_time}\n')
total_time = endInstallTime - startInstallTime
print(f'安装耗时:{total_time}')
else:
print('apk安装Fail, 请check是否已安装过.')
# 如果拖入的是一个文件夹
else:
okCount, failCount = (0, 0)
apklist = list()
for file in os.listdir(path):
# if os.path.splitext(file)[1] == '.apk':
if file.endswith('.apk'):
apklist.append(file)
print(f'有{len(apklist)}个apk待安装.')
os.chdir(path)
filepath, file = os.path.split(path)
for i in range(len(apklist)):
if apklist[i].count(' ') != 0:
apklist[i] = '\"' + apklist[i] + '\"'
cmdinstall = 'adb install -t ' + apklist[i]
print(f'当前{getnowdatatime(2)}正在安装第{i+1}个apk:{apklist[i]}')
startInstallTime = getnowdatatime()
if subprocess.run(cmdinstall).returncode == 0:
print(f'第{i+1}个apk已安装成功!')
endInstallTime = getnowdatatime()
print(f'安装开始时间:{startInstallTime}')
print(f'安装完成时间:{endInstallTime}\n')
okCount = okCount + 1
else:
failCount = failCount + 1
print('此apk安装fail, 请check是否已安装过.')
print(f'所有应用共{len(apklist)}个, 已成功安装: {okCount}个,fail: {failCount}个.')
except KeyboardInterrupt:
print('\n手动中止操作:KeyboardInterrupt')
except EOFError:
print('\n未知异常: EOFError')