[英]Python Error: "AttributeError: __enter__"
所以,我無法加載我的 json 文件,我不知道為什么,誰能解釋我做錯了什么?
async def give(msg, arg):
if arg[0] == prefix + "dailycase":
with open("commands/databases/cases.json", "r") as d:
data = json.load(d)
出於某種原因,我收到此錯誤:
with open("commands/databases/cases.json", "r") as d:
AttributeError: __enter__
最有可能的是,您已將 Python內置open
函數重新分配給代碼中的其他內容(幾乎沒有其他合理的方式可以解釋此異常)。
然后with
語句將嘗試將其用作上下文管理器,並在首次進入with
塊時嘗試調用其__enter__
方法。 這會導致您看到錯誤消息,因為您的對象open
,無論它是什么,都沒有__enter__
方法。
在 Python 模塊中查找要重新分配open
。 最明顯的是:
def open(..)
open =
直接重新分配from foo import open
或import something as open
該函數是最有可能的嫌疑人,因為看起來您的open
實際上是一個可調用的。
為了幫助您找到意外綁定的對象open
,您還可以嘗試
print('open is assigned to %r' % open)
緊接在您的with
語句之前。 如果它沒有顯示<built-in function open>
,你就找到了罪魁禍首。
我在這一行收到此錯誤:
with concurrent.futures.ProcessPoolExecutor as executor:
缺少括號是問題
with concurrent.futures.ProcessPoolExecutor() as executor:
就我而言,我是故意用定義函數調用秒表定制
with stopwatch('upload %d bytes' % len(data)):
...code...
所以不得不補充:
import contextlib
並為自定義函數定義添加前綴,如下所示:
@contextlib.contextmanager
def stopwatch(message):
...code...
我的問題是我期待os.open
像內置的open
一樣工作......
這導致AttributeError: __enter__
import os
with os.open('out.txt', os.CREAT) as f:
f.write('hello world')
這不
with open('out.txt', 'w') as f:
f.write('hello world')
我想很容易導致from os import open
出現 OP 問題。
檢查您的python版本,OP的語法僅在3.8+中支持
我默認的 Python 3.6 Ubuntu 安裝需要不同的分析語法,如下所述(當從下拉列表中選擇 3.6 版時): https : //docs.python.org/3.6/library/profile.html#module-cProfile
效果很好:
import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
# optional for better viz
ps.dump_stats(filename='needs_profiling.prof')
建議:用snakeviz交互式地可視化這個。
sudo pip3 install snakeviz
snakeviz ./needs_profiling.prof
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.