如何调试需要stdin的python CLI? [英] How to debug python CLI that takes stdin?

查看:188
本文介绍了如何调试需要stdin的python CLI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调试我编写的Python CLI,该CLI可以从stdin中获取其参数。一个简单的测试用例的输出为

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.py

等于

python mytool.py test

我想调试此工具的某些问题,所以我尝试运行此工具:

I'd like to debug some issues with this tool, so I tried to run this:

echo "test" | pdb mytool.py

但是我得到此输出,然后pdb退出:

But I get this output, then pdb exits:

> /path/to/mytool.py(5)<module>()
-> '''
(Pdb) *** NameError: name 'test' is not defined
(Pdb)

当我在shebang中添加 -m python 时,如果运行 pdb.set_trace(),也会发生相同的情况

The same thing occurs when I add -m python to the shebang, and if I run pdb.set_trace() inside the script.

这里发生了什么?

推荐答案

另一个选择是创建您自己的Pdb对象,并在那里设置stdin和stdout。我的概念证明涉及2个终端,但是可以肯定的是,可以合并某些非常不安全的网络服务器。

Another option is to create you own Pdb object, and set there the stdin and stdout. My proof of concept involves 2 terminals, but for sure some work can be merged some kind of very unsecure network server.


  1. 创建两个fifo:

    mkfifo fifo_stdin
    mkfifo fifo_stdout

在一个终端中,在后台打开stdout,然后写到stdin:

cat fifo_stdout&
猫> fifo_stdin

In one terminal, open stdout on background, and write to stdin: cat fifo_stdout & cat > fifo_stdin

您应该能够在第一个控制台上使用pdb。

You should be able to use pdb on the first console.

唯一的缺点是必须使用自定义pdb,但是在初始化时进行一些猴子修补(PYTHONSTARTUP或类似的操作)可以帮助:

The only drawback is having to use your custom pdb, but some monkey patching at init (PYTHONSTARTUP or similar) can help:


import pdb
mypdb = pdb .pdb(stdin = open('fifo_stdin','r'),stdout = open('fifo_stdout','w'))
pdb.set_trace = mydbp.set_trace

这篇关于如何调试需要stdin的python CLI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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