gpt4 book ai didi

python 错误。我不明白我做错了什么

转载 作者:太空宇宙 更新时间:2023-11-04 07:23:29 24 4
gpt4 key购买 nike

我对自己做错了什么很迷茫...我已经在网上搜索了几个小时,尝试重新格式化我的代码,但现在我只是觉得卡住了。

这是我的代码:

import httplib
import json

urlBase = 'amoeba.im'
token = False
username = raw_input('Username? ')

connection = httplib.HTTPConnection(urlBase)

def get(url):
connection.request("GET", url)
response = connection.getresponse()
print response.status, response.reason
print response.read();
if token == False:
token = response.read()
token = token.split('"token":"')[1]
token = token.split('","')[0]
print token

get('/api/login?username=' + username)

get('/api/rooms/join?room=#lobby&token=' + token)

get('/api/postmessage?message=hello%20world&token=' + token)

connection.close()

这是终端输出:

Tyler-Keohanes-MacBook-Pro:~ tylerkeohane$ clear && '/usr/bin/pythonw' '/Users/tylerkeohane/Desktop/chatbot.py'
Username? TgwizBot
200 OK
{"success":true,"username":"TgwizBot","token":"103f6a2809eafb6","users":[{"username":"razerwolf","seen":1338582178260},{"username":"tonynoname","seen":1338582178028},{"username":"arrum","seen":1338582177804},{"username":"Valerio","seen":1338582177504},{"username":"Tgwizman","seen":1338582177258},{"username":"tonynoname2","seen":1338582178004},{"username":"TgwizBot","seen":1338582182219}],"time":1338582182219}
Traceback (most recent call last):
File "/Users/tylerkeohane/Desktop/chatbot.py", line 21, in <module>
get('/api/login?username=' + username)
File "/Users/tylerkeohane/Desktop/chatbot.py", line 15, in get
if token == False:
UnboundLocalError: local variable 'token' referenced before assignment
Tyler-Keohanes-MacBook-Pro:~ tylerkeohane$

有人可以帮忙吗? :(

最佳答案

线索在这里:

UnboundLocalError: local variable 'token' referenced before assignment

您需要将 token 声明为全局的:

def get(url):
global token
...

您可能还想考虑避免使用全局变量,因为它们通常被认为是一种不好的做法。

关于 python 错误。我不明白我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10856954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com