Why do I get an error "AttributeError: module 'pprint' has no attribute 'PrettyPrinter'

Why do I get an error "AttributeError: module 'pprint' has no attribute 'PrettyPrinter'

我正在尝试使用 pprint 打印出我的 yaml 文件中的值,尽管安装了 pprint 并导入了所有内容,但我 运行 还是遇到了这个错误

    #!/bin/python

    import yaml
    import subprocess
    import os
    import pprint

    pp = pprint.PrettyPrinter(indent=4)



    #pre-requisite-run the script in an empty directory

    #read data from the config yaml file
    def read_yaml(file):
        with open(file, "r") as stream:
            try:
                config = yaml.safe_load(stream)
                # print(config)
            except yaml.YAMLError as exc:
                print(exc)
                print("\n")
        return config

    d = read_yaml("config.yaml")

    #print out contents of the yaml file with a better structure
    pp.pprint(d)

当我在命令行中 运行 时出现错误消息:

    Traceback (most recent call last):
      File "pprint.py", line 6, in <module>
        import pprint
      File "../pprint.py", line 8, in <module>
        pp = pprint.PrettyPrinter(indent=4)
    AttributeError: module 'pprint' has no attribute 'PrettyPrinter'

您的文件被命名为 pprint.py 从而掩盖了您要使用的 pprint 模块。将您的文件重命名为不同的名称。