【问题标题】:Attribute error Cmd module属性错误 Cmd 模块
【发布时间】:2014-03-24 02:45:29
【问题描述】:

我正在尝试使用 python 的 cmd 模块,我在一个网站上得到了这个测试代码 在 python 3.2 中编译此代码时

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()

我收到 cmd 模块的此错误。

AttributeError: 'module' object has no attribute 'Cmd'

在第 4 行。

【问题讨论】:

  • 你好,我试过你的代码,没有发现错误...顺便问一下,你调用的函数 cmdloop() 在哪里?
  • @lowitty 是 cmd.Cmd 的方法。在 python 3.3 上工作正常。
  • @m.wasowski 谢谢!其实我试过这个脚本并得到输出:(Cmd)并且没有错误。
  • 所以它不能在 python 3.2 上运行?

标签: python cmd attributeerror


【解决方案1】:

我用python3.2.3 尝试了你的脚本,它成功了。您在该文件所在的同一目录中是否有一个名为 cmd.py 的文件?如果你这样做了,那么import cmd 将不会导入正确的模块。相反,它会在当前目录中导入cmd.py

我在目录中创建了一个名为 cmd.py 的文件,但遇到了与您尝试运行脚本时相同的错误。所以删除当前目录中的cmd.py,或者如果你有它的话,将它命名为其他名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 2021-07-17
    • 2021-09-25
    • 2018-01-21
    相关资源
    最近更新 更多