在pdb模式下运行shell命令

14
我想在Python调试器中运行cd和ls命令。我尝试使用!ls,但是我收到以下错误信息:*** NameError: name 'ls' is not defined。

2
这不是一个操作系统的 shell。如果你想运行系统命令,请使用 subprocess 模块。 - Klaus D.
3个回答

13

只需使用“os”模块,您就可以轻松地在pdb中执行任何操作系统命令。

首先:

(Pdb) import os

然后:

(Pdb) os.system("ls")

甚至可以使用以下命令:

(Pdb) os.system("sh")

最新的命令只是生成一个子shell。退出它将返回到调试器。

注意:当使用os.system("cd dir")时,“cd”命令不会产生任何效果,因为它不会更改python进程的cwd。要更改目标目录,请使用os.chdir("/path/to/targetdir")


4
很遗憾,PDB不能运行shell命令。你看到的错误原因是PDB允许您检查变量名或使用运行一行代码片段。从文档中引用:

[!]statement

Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To set a global variable, you can prefix the assignment command with a global command on the same line, e.g.:

(Pdb) global list_options; list_options = ['-l']
(Pdb)
因此,!ls的意思是“打印ls的值”,这导致了你观察到的NameError错误。

2

PDB的工作方式与正常的Python控制台非常相似,因此可以像在Python交互式会话中一样导入和使用包。

关于目录列表,您应该使用os模块(在PDB中,每行都要确认并按下回车键;):

from os import listdir
os.listdir("/path/to/your/folder")

如果您想进行更高级的操作,例如启动新进程或捕获输出等,则需要查看 subprocess模块。


嗯,没错...也许我表达不够清楚,你可以在PDB中全部使用它...就像你通常在控制台中做的那样。 - Mr.Coffee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接