Variable alternates whether or not it exists in Python Debugger

后端 未结 2 1389
南方客
南方客 2021-01-22 00:05

Can anyone explain this? (Python 2.7, Django 1.7)

foo = data[\'selected_items\']
(Pdb) foo
(Pdb) *** NameError: name \'foo\' is not defined
foo
(Pdb) u\'1,2\'
fo         


        
相关标签:
2条回答
  • 2021-01-22 00:44

    You have two threads which stopped at the same breakpoint.

    So basically, there are two instances of pdb, competing for your prompt, i.e. your prompts are alternating between the different threads. You first assign to the name foo in one, than the other one gets a chance to run, knowing nothing about foo, then when you press enter, the other is back, with foo defined.

    The best indicator that this is the case is that your prompt is not aligned with your commands and their outputs. Instead of:

    <PROMPT> COMMAND
    OUTPUT
    <PROMPT> COMMAND
    OUTPUT
    

    You see:

    COMMAND
    <PROMPT> OUTPUT
    COMMAND
    <PROMPT> OUTPUT
    

    Everytime you press enter, the "other" thread sneaks in its prompt before the "first" thread manages to write its output.


    EDIT

    A simple way to reproduce in a standalone, without django:

    from threading import Thread
    
    def f(x):
        import pdb; pdb.set_trace()
        while True: pass
    
    t1 = Thread(target=lambda: f(1))
    t2 = Thread(target=lambda: f(2))
    t1.start(); t2.start()
    
    (Pdb) x
    2
    (Pdb) x
    1
    
    0 讨论(0)
  • 2021-01-22 00:45

    When the statement appears in PDB, it hasn't actually been executed yet. It will be executed once you use 'next'.

    0 讨论(0)
提交回复
热议问题