Use pdb.set_trace() in a script that reads stdin via a pipe

前端 未结 6 1562
我寻月下人不归
我寻月下人不归 2020-12-05 04:20

I have a python script that reads stdin via a pipe, and I cannot seem to use it with pdb.set_trace().

my_script.py:

#!/usr/bin/env python
import sy         


        
相关标签:
6条回答
  • 2020-12-05 04:45

    For completeness, I made a snippet with the following code, based on the accepted answer.

    import sys; sys.stdin = open('/dev/tty'); import pdb; pdb.set_trace();
    
    0 讨论(0)
  • 2020-12-05 04:53

    The thing is: cat will not stop sending data because your script is currently debugging. And when you going to trace, then stdin is still filled by cat + your keyboard. You need to choose one of them.

    You can read the whole stdin, and then, set_trace() will be not filled by stdin:

    sys.stdin.read()
    pdb.set_trace()
    
    0 讨论(0)
  • 2020-12-05 04:54

    Here's an example of what worked for me:

    import sys
    import pdb
    
    lines = sys.stdin.readlines()
    sys.stdin = open("/dev/tty")
    pdb.set_trace()
    

    Edit: since 3.7 you no longer need to import pdb for set_trace, it is available as breakpoint, so the above only requires a sys import.

    import sys
    
    lines = sys.stdin.readlines()
    sys.stdin = open("/dev/tty")
    breakpoint()
    

    You may wish to replace sys.stdin.readlines() above with the iterable fileinput.input() (which defaults to sys.stdin if the list of files in sys.argv[1:] is empty) like so:

    import fileinput
    import sys
    
    lines = fileinput.input()
    sys.stdin = open("/dev/tty")
    breakpoint()
    
    0 讨论(0)
  • 2020-12-05 04:59

    Using the ripdb module (pip install ripdb) solved this issue for me.

    0 讨论(0)
  • 2020-12-05 05:01

    You may want to look at how the Celery RDB (Remote Debugger) contrib module works:

    https://github.com/celery/celery/blob/master/celery/contrib/rdb.py

    It seems to involve a lot of stream processing, but I have tested it, and it works by allowing you to telnet into a new local network port. It's not the much better ipdb, but simply pdb.

    0 讨论(0)
  • 2020-12-05 05:09

    I ran into this exact problem today. I found that Winpdb works perfectly.

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