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

如有帮助,敬请采纳,你的采纳是我前进的动力,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)

你的open_time变量是在if里面定义的
if如果没有走,那你的open_time就没有定义呀
所以你需要在一开始给open_time一个初值,让它不管走不走if都有值

你的opentime定义到for循环了所以不对,变量是由作用域范围的

因为你循环中if 'TotalTime' in line:判断一次也没有成立, 没有找到包含TotalTime的行
open_time 变量一直都没有被赋值创建
下边 return int(open_time) 访问open_time就是未定义
你检查数据中是否有包含TotalTime的行,TotalTime有没有写错
如果需要有,"没找到包含TotalTime的行"的情况,用下边方式处理

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]
            break
    else:
        print('错误没有找到包含TotalTime的行')
        return -1
    return int(open_time)

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

cpu_dataList = re.split('\n', cpu_result)这一句似乎不对,re没有定义。看样子你是写类似php的语法格式过来的
估计你是想把cpu result分割开,建议这样试试:
cpu_dataList = cpu_result.split('\n')

变量作用域的问题, 把 open_time 在最上面赋一个默认值0就行, 直接变成全局变量就不会有这个问题了

请看👉 :Python的类定义,实例化
for line in cpu_dataList:
        if 'TotalTime' in line:
            open_time = re.split(':', line.replace(' ', ''))[1]
    return int(open_time)

if 为 True 存在 open_time,为False该变量不存在
解决方法

  • 添加 else判断
  • 在if 前 定义变量open_time
    '''check response code'''
    if json.loads(res)['code'] == 0:
        try:
            ota_status = json.loads(res)['data'][id]
        except KeyError:
            result = 'unRegistered'
        else:
            '''check token'''
            if len(ota_status) > 100:
                otaPASS = otaPASS + 1
                result = 'Pass'
            else:
                otaFail = otaFail + 1
                result = 'Fail'
    else:
        otaFail = otaFail + 1
        result = 'Fail'
  ota_dic[id] = result

代码问题出在如下代码了

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

在python 中变量是有作用域的,然后你们前面说的都没问题,只是有个前提,就是

 if 'TotalTime' in line:

必须为True 的时候这个时候 open_time 才会被定义并赋值... 反之这个 if 判断不为 True 时,也就是

open_time = re.split(':', line.replace(' ', ''))[1]

压根儿就不会执行,因此也就不存在 open_time 定义和赋值了。
所以也就会存在你说的 open_time 变量未定义的错误了...

为了验证,你可以简单执行如下代码进行验证,

for i in range(1):
    const = 3
    if const ==2:
        variable = "我被定义并赋值了 ^v^ "
        print (variable)

print ("******")
print (variable)

最后针对这个有异议的,可以消息。