我想在Python调试器中运行cd和ls命令。我尝试使用!ls,但是我收到以下错误信息:*** NameError: name 'ls' is not defined。
只需使用“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")。
!
运行一行代码片段。从文档中引用:
因此,
[!]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错误。PDB的工作方式与正常的Python控制台非常相似,因此可以像在Python交互式会话中一样导入和使用包。
关于目录列表,您应该使用os模块(在PDB中,每行都要确认并按下回车键;):
from os import listdir
os.listdir("/path/to/your/folder")
如果您想进行更高级的操作,例如启动新进程或捕获输出等,则需要查看 subprocess模块。