How to debug python CLI that takes stdin?

前端 未结 4 832
悲&欢浪女
悲&欢浪女 2020-12-28 14:08

I\'m trying to debug a Python CLI I wrote that can take its arguments from stdin. A simple test case would have the output of

echo \"test\" | python mytool.p         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 15:04

    You can use another file descriptor. With bash you can create a new file descriptor with:

    exec 3<> test.txt
    

    And then on your python file have something like:

    #!/usr/bin/python
    
    # Use fd 3 as another stdin file.
    import os
    stdin=os.fdopen(3)
    
    while True:
        s=stdin.readline()
        import pdb; pdb.set_trace()
        print len(s)
    

    Just runing your script will use that test.txt as input, and you can use stdin on stdin. It can be used as well with pipes if you need.

提交回复
热议问题