属性错误 Cmd 模块
我正在尝试使用Python的cmd模块,并在一个网站上找到了这段测试代码。
import cmd
import os
class ShellEnabled(cmd.Cmd):
last_output = ''
def do_shell(self, line):
"Run a shell command"
print ("running shell command:", line)
output = os.popen(line).read()
print (output)
self.last_output = output
def do_echo(self, line):
"Print the input, replacing '$out' with the output of the last shell command"
# Obviously not robust
print (line.replace('$out', self.last_output))
def do_EOF(self, line):
return True
if __name__ == '__main__':
ShellEnabled().cmdloop()
当我在Python 3.2中运行这段代码时,出现了cmd模块的错误。
AttributeError: 'module' object has no attribute 'Cmd'
错误出现在第4行。
2 个回答
-1
我觉得有一个叫cmd.py的文件。试着把它删掉,然后再试试。这样就能正常工作了。
8
我用 python3.2.3
试了你的脚本,结果是可以运行的。你在这个文件所在的文件夹里,有没有一个叫 cmd.py
的文件?如果有的话,使用 import cmd
就不会导入正确的模块了。它会导入当前文件夹里的 cmd.py
。
我在这个文件夹里创建了一个叫 cmd.py
的文件,结果在运行你的脚本时遇到了和你一样的错误。所以,如果你那里有这个 cmd.py
文件,要么把它删掉,要么把它改个名字。