2012-06-01 47 views
1

我很迷茫,我做错了什么......我已经搜索了几个小时的网络,试图重新格式化我的代码一堆,然后现在我只是觉得卡住了。Python错误。我不明白我在做什么错

这是我的代码:

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$ 

谁能帮助? :(

+1

可能的重复的[UnboundLocalError在Python](http://stackoverflow.com/questions/9264763/unboundlocalerror-in-python) – senderle

+0

我会补充说,如果你谷歌“unboundlocalerror”,[这](http:///eli.thegreenplace.net/2011/05/15/understanding-unboundlocalerror-in-python/)是第一个结果。 – senderle

回答

6

的线索是在这里:

UnboundLocalError: local variable 'token' referenced before assignment 

您需要声明token作为一个全球性的:

def get(url): 
    global token 
    ... 

您也可能要考虑避免全局变量,因为它们通常被认为是一个不好的做法

1

你在你的函数中赋值为token,所以它被认为是该函数的局部变量,因为错误信息表示在你有任何东西之前,你已经尝试过使用它。

您在函数外声明的token被本地变量“隐藏”,因此无法访问。

要使其在函数中可分配,请在def行后面加上global token

但全局变量通常是一个糟糕的设计的标志。相反,您应该将token作为参数传递给该函数。

如果你只是使用requests模块,你会发现生活变得更容易。

相关问题