2014-11-06 60 views
1

我正在嘗試編寫一個使用json和請求模塊的腳本。在我編寫腳本之前,我在玩交互式shell的命令,並且爲我的代碼創建了一個實際的文件,所有事情都以某種方式破壞了。我第一次運行代碼時,文件夾中出現了一個pycache文件夾,我認爲這是以某種方式破解everthing。該代碼在shell中逐行運行時,不再適用於此文件夾存在pycache文件夾。我的代碼如下:在Python中導入模塊時出現AttributeError 3

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的:‘模塊’對象有沒有屬性‘傾銷’在此文件夾,我以前也。有另一個程序使用外部模塊,也沒有長期與pycache文件夾的存在,所以我幾乎可以肯定,它是造成的問題。但是,刪除它並沒有解決任何問題,因爲代碼仍然沒有工作,它只是被重新創建。

編輯:該問題已通過刪除整個buggy目錄並重寫所有內容來解決。

+0

您之前正在進行某種測試嗎?嘗試使用'python -B'運行,看看這是否能解決問題。 – Anzel 2014-11-06 19:05:37

回答

0

請參閱本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 

或者,設置環境變量:

PYTHONDONTWRITEBYTECODE = 1 
+0

我看到了答案,並用-B標誌運行python,雖然它阻止創建__pycache__文件夾,但AttributeError仍然顯示。設置環境變量也沒有幫助。 – thenorm 2014-11-06 19:39:41

+0

你是否在virtualenv?在你的情況下可能需要重新安裝 – Anzel 2014-11-06 19:41:31

+0

什麼是virtualenv?另外python本身不是問題,如果我改變到另一個目錄一切都很好。我應該刪除文件夾並重試所有內容嗎? – thenorm 2014-11-06 20:01:33

1

'module' object has no attribute 'xxx'的最常見原因,其中'xxx'是您'知道''模塊'具有的屬性,是這樣的:您的公關ogram在一個目錄中有一個'module.py',你已經忘記了該模塊。因此import module會導入您的模塊而不是stdlib(或其他地方)中的預期模塊。在python-list上發佈了這個問題的多個例子。至少有兩個是由於在同一個目錄中被遺忘的關於random.py造成的。

如果您發佈了回溯,情況會更加清晰。

相關問題