Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyCharm: How can I use breakpoints in multithreaded code?

I want to use PyCharm, but I really need to use breakpoints in threads other than the main thread.

In this example code, PyCharm does not break within the threaded function. Is there a way to fix that?

import time, threading
def f():
    while True:
        time.sleep(1.0)
        print 'tick-tock' # Put a breakpoint here...

th = threading.Thread(target=f)
th.start()
time.sleep(30)
print 'done.'

Edit: Platform details: Mac OS 10.9, Python 2.7.6, PyCharm 3.4.1

like image 788
Stuart Berg Avatar asked Jun 12 '14 20:06

Stuart Berg


People also ask

Why it is difficult to Debug multi threaded programs?

Parallel processing using many threads can greatly improve program performance, but it may also make debugging more difficult because you're tracking many threads. Multithreading can introduce new types of potential bugs.

How do I Debug multiple threads in Intellij?

Start the debug session by clicking the Run button near the main method and selecting Debug. When the program has run, both threads are individually suspended in the addIfAbsent method. Now you can switch between the threads (in the Frames or Threads tab) and control the execution of each thread.


1 Answers

This seems to work for me:

#!/usr/bin/python

import time
import threading
import pdb

def f():
    while True:
        time.sleep(1.0)
        print 'tick-tock' # Put a breakpoint here...
        pdb.set_trace()

th = threading.Thread(target=f)
th.start()
time.sleep(30)
print 'done.'

During execution:

┌───┤/tmp├──────────────────────────────────────┤0.43├──────┤20140612.211049├───
└─┤goncalog@darkside:pts/1│ret=1├────> python test.py 
tick-tock
> /tmp/test.py(8)f()
-> while True:
(Pdb) list
  3     import time
  4     import threading
  5     import pdb
  6     
  7     def f():
  8  ->     while True:
  9             time.sleep(1.0)
 10             print 'tick-tock' # Put a breakpoint here...
 11             pdb.set_trace()
 12     
 13     th = threading.Thread(target=f)
(Pdb) c
tick-tock
> /tmp/test.py(8)f()
-> while True:
(Pdb) 
like image 102
Goncalo Avatar answered Oct 04 '22 00:10

Goncalo