Python变量在pdb和print语句中的评估不同 [英] Python variable is evaluated differently in pdb and print statements

查看:168
本文介绍了Python变量在pdb和print语句中的评估不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python程序中使用线程,最近发现一个浮点不正确解释的问题,每当我在pdb或logging语句中打印出来时,大部分时间都会正确显示。



奇怪的是,在刚刚运行的这两个线程中,会出现不同的打印数量。另外前两个打印使用相同的格式,但该值仍然在线程1中更改。

  for x in imports:
如果float(x.prob)== 0.0:
logging.debug(float(x.prob))
logging.debug(float(x.prob))
logging.debug (x.prob)
logging.debug(str(x.prob))
logging.debug(str(float(x.prob)))
import pdb; pdb.set_trace()

[DEBUG](Thread-1)0.0
[DEBUG](Thread-1)0.0592
[DEBUG](Thread-1)0.0592
[DEBUG](Thread-1)0.0592
[DEBUG](Thread-1)0.0592
[DEBUG](Thread-2)0.0
[DEBUG](Thread-2)0.0
[DEBUG](Thread-2)0
[DEBUG](Thread-2)0.0592
[DEBUG](Thread-2)0.0592

 (Pdb)float(x。 prob)== 0.0 
False

原因是什么?
我可以做什么,这是第一次正确解释?



类似于这个问题: pdb显示与print语句不同的变量值

解决方案

很不可能从你发布的内容中得知。浮动不能随机从0.0转换到〜0.05,有些东西正在改变存储在该存储单元(变量)中的值。您是否从其他线程设置值?



另外,请注意,在演示代码中,如果要查找x.prob的值为0.0592,一开始,它将在if语句中失败相等性测试,从不触发打印语句。


I am using threads in a python program and recently found a problem where a float is not being interpreted correctly and whenever I go to print it out in pdb or in a logging statement, it shows up correctly most of the time.

Oddly, it takes a different amounts of prints to show up in these two threads I just ran. Also the first two prints use the same format, but the value still changes in thread 1.

for x in imports:
    if float(x.prob) == 0.0:
        logging.debug(float(x.prob))
        logging.debug(float(x.prob))
        logging.debug(x.prob)
        logging.debug(str(x.prob))
        logging.debug(str(float(x.prob)))
        import pdb; pdb.set_trace()

[DEBUG] (Thread-1  ) 0.0
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-1  ) 0.0592
[DEBUG] (Thread-2  ) 0.0
[DEBUG] (Thread-2  ) 0.0
[DEBUG] (Thread-2  ) 0
[DEBUG] (Thread-2  ) 0.0592
[DEBUG] (Thread-2  ) 0.0592

and

(Pdb) float(x.prob) == 0.0
False

What is the cause? what can I do so it's interpreted correctly the first time?

Similar to this question: pdb show different variable values than print statements

解决方案

Its pretty impossible to tell from what you've posted. Floats don't switch from 0.0 to ~0.05 randomly, something is changing the value stored in that memory location (variable). Are you setting the value from other thread?

Also, be aware that in your demo code, if you're looking for x.prob to have the value of 0.0592 from the beginning, it will fail the equality test in the if statement and never trigger your print statements.

这篇关于Python变量在pdb和print语句中的评估不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆