首页 > 解决方案 > 为什么我会收到错误“AttributeError:模块'pprint'没有属性'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'

标签: pythonpprint

解决方案


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


推荐阅读