在Python3中导入模块时发生AttributeError

2024-10-02 02:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个使用json和requests模块的脚本。在我写这个脚本之前,我在交互式shell上玩命令,自从为我的代码创建了一个实际的文件之后,一切都不知怎么地坏了。第一次运行代码时,文件夹中出现了一个pycache文件夹,我认为这会破坏一切。当在shell中逐行运行时,代码不再适用于这个pycache文件夹。我的代码如下:

import json
import requests
r = requests.get('http://api.wunderground.com/api/78c2f37e6d924b1b/hourly/q/CA/Berkeley.json')
data = json.loads(r.text)
for x in range(0, 35):
    print(data['hourly_forecast'][x]['FCTTIME']['hour'])

这应该打印出天气预报中的所有小时数,但是我得到一个“AttributeError:'module”对象没有属性“dumps”。在这个文件夹中,我以前也有另一个程序,它使用外部模块,但也不能长期与pycache文件夹一起工作,所以我几乎可以肯定是它导致了问题。但是,删除它并不能修复任何问题,因为代码仍然不起作用,它只会被重新创建。在

编辑:通过删除整个buggy目录并重写所有内容,问题得到了解决。在


Tags: 模块文件代码import命令脚本文件夹api
2条回答

'module' object has no attribute 'xxx',其中“xxx”是您“知道”module“拥有的属性,最常见的原因是:您的程序所在的目录中有一个'模块.py“你已经忘了这个。因此,import module导入您的模块,而不是stdlib(或其他地方)中预期的模块。在python列表上已经有多个这个问题的例子。至少有两个是因为随机.py在同一个目录中。在

如果你公布了回溯,情况会更清楚。在

请参考这个SO问题What is pycache?,请参见@scott_fakename的回答:

When you run a program in python, the interpreter compiles it to bytecode first (this is an oversimplification) and stores it in the pycache folder. If you look in there you will find a bunch of files sharing the names of the .py files in your project's folder, only their extentions will be either .pyc or .pyo. These are bytecode-compiled and optimized bytecode-compiled versions of your program's files, respectively.

As a programmer, you can largely just ignore it... All it does is make your program start a little faster. When your scripts change, they will be recompiled, and if you delete the files or the whole and run your program again, they will reappear (unless you specifically suppress that behavior)

If you are using cpython (which is the most common, as it's the reference implementation) and you don't want that folder, then you can suppress it by starting the interpreter with the -B flag, for example

python -B foo.py

Another option, as noted by tcaswell, is to set the environment variable PYTHONDONTWRITEBYTECODE to any value (according to python's man page, any "non empty string").

因此,您可以运行:

python -B xxx.py

或者,设置环境变量:

^{pr2}$

相关问题 更多 >

    热门问题