TikL362 2022-07-14 17:26 采纳率: 0%
浏览 165
已结题

python报错:变量没有定义

使用adb命令来打开程序并获取程序的启动时间等信息,明明定义了变量,为什么会报错说变量没有定义呢?

问题相关代码test2.py 如下:

import re
import subprocess
import time


def get_open_time(cpu_result):
    cpu_dataList = re.split('\n', cpu_result)
    for line in cpu_dataList:
        if 'TotalTime' in line:
            open_time = re.split(':', line.replace(' ', ''))[1]
    return int(open_time)


process_name_dict = {'百度地图': 'com.baidu.naviauto/com.baidu.naviauto.NaviAutoActivity'}
app_cold_dict = {}

for key, value in process_name_dict.items():
    cold_time_list = []
    for i in range(int(1)):
        adb_result = subprocess.Popen('adb shell am start -W -n' + str(value), shell=True,
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        time.sleep(2)
        time_result = ''
        for line in adb_result.stdout.readlines():
            print(line)
            time_result += line.decode().replace('\r', '')
            print(time_result)
            app_start_time = get_open_time(time_result)
            cold_time_list.append(app_start_time)

print(cold_time_list)

运行结果及报错内容

img

  • 写回答

9条回答

  • 脚踏南山 2022-07-14 21:35
    关注
    获得1.10元问题酬金

    如有帮助,敬请采纳,你的采纳是我前进的动力,O(∩_∩)O谢谢!!!!!!!!
    建议打印line,观察观察在根据需求设计代码。

    def get_open_time(cpu_result):
        cpu_dataList = re.split('\n', cpu_result)
        for line in cpu_dataList:
            print(line)
            if 'TotalTime' in line:#注意这行,当所有line中都不包含 'TotalTime'时,open_time未被定义
                open_time = re.split(':', line.replace(' ', ''))[1]
        return int(open_time)
    
    评论

报告相同问题?

问题事件

  • 系统已结题 7月22日
  • 修改了问题 7月14日
  • 创建了问题 7月14日