如果python中的函数发生错误,有没有办法访问变量的值?

如果python中的函数发生错误,有没有办法访问变量的值?,python,jupyter,Python,Jupyter,这是我的函数,在执行过程中出错。那么,在发生错误的那一行之前,有没有办法访问变量的值呢? 就像这里的错误发生在“df=DataFrame({'real\u rating':real\u rating,'predicted\u rating':predicted\u rating})”上,所以我想访问real\u rating和predicted\u rating变量的值 def calc_MAE_system(targetClusterTestUserDict,final_clusters):

这是我的函数,在执行过程中出错。那么,在发生错误的那一行之前,有没有办法访问变量的值呢? 就像这里的错误发生在“
df=DataFrame({'real\u rating':real\u rating,'predicted\u rating':predicted\u rating})
”上,所以我想访问
real\u rating
predicted\u rating
变量的值

def calc_MAE_system(targetClusterTestUserDict,final_clusters):
    real_rating=[]
    predicted_rating=[]

    for i in range(0,length):
      real_rating.append(test.iloc[i]['rating'])
      temp_rating=predict_rating(final_clusters,test.iloc[i]['userId'],userBelongsToCluster,test.iloc[i]['movieId'],temp_df_rating)
      predicted_rating.append(temp_rating)


    df = DataFrame({'real_rating': real_rating, 'predicted_rating': predicted_rating})
    df.to_csv("rating_comparison_online_phase.csv", sep='\t')


    if(length != 0):
      mae=sum/length
    else:
      mae=0

    return mae

当然,您可以使用“try”和“except”。如果“try”中的代码不起作用,它将使用“except”中的代码。 例如

如果无法创建数据框,它将打印如下内容:

Error: real_rating = xxxxx, predicted_rating = yyyy

是的,但为此我必须再次运行代码,但我现在想访问它本身?当然。如果您现在想从上一次运行中获取这些值,那么必须将它们记录在某个位置,而我尝试的另一种方法是,将函数变量声明为全局变量。e、 g
global var\u name
Error: real_rating = xxxxx, predicted_rating = yyyy