2016-05-23 35 views
1

我想更新一個全局變量AUTHEN它引用了套接字的輸入流。Python全局變量修改不起作用

run()方法中,我試圖修改AUTHEN的值。但是,當我真正運行程序時,它永遠不會改變。我相信我的服務器確實派比「東西」以外的其他消息

import threading 
import sys 
import time 
import socket 
import ssl 

AUTHEN ="Something" 
class timer(threading.Thread): 

    def __init__(self): 
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     self.ssl_sock = ssl.wrap_socket(self.sock, ssl_version=ssl.PROTOCOL_SSLv23) 
     self.ssl_sock.connect(('localhost',9991)) 
     self.isrun = True 
     threading.Thread.__init__(self) 


    def send(self,str): 
     self.ssl_sock.send(str + "\n") 


    def run(self): 
     global AUTHEN 
     while self.isrun: 
      receive = self.ssl_sock.recv(1024) 
      AUTHEN = receive 
      print("recv ->" +AUTHEN) 
     self.sock.close() 
     self.ssl_sock.close() 


    def close(self): 
     self.isrun == False 


    def authentication(self,username,password): 
     global AUTHEN 
     print "Verifing identity" 
     self.ssl_sock.send("U&P"+"sprt"+username+"sprt"+password+'\n') 
     while (True): 
      print AUTHEN 
      if(AUTHEN == str("OK\r\n")): 
       return AUTHEN 
      else: 
       print "Please Try again" 
       break 

def main(): 
    client = timer() 
    client.start() 

#LOG IN 
while(True): 
    loginMessage = str(raw_input("Please enter username and password as following format: \n username%password \n")) 
    username = loginMessage.split("%")[0] 
    password = loginMessage.split("%")[1] 
    Result = client.authentication(username,password) 
    if(Result == str("OK\r\n")): 
     print "LOG IN SUCCESSFULLY" 
     print "Welcome:\n","Command to be used:\n","-a filename\n" "-c number\n", "-f filename\n","-h hostname:port\n","-n name\n","-u certificate\n","-v filename certificate\n","otherwise input will be treated as normal message" 
     break 
if __name__=='__main__': 
main() 

謝謝。

+4

你爲什麼要使用Python半冒號? – anand

+0

@anand java習慣... – bslqy

+0

在python中,像python一樣做;還要指定你正在使用的Python版本。 – anand

回答

0

你需要調用的main()

你需要開始()你的線程以初始化運行(),這將設置你的全局變量。你的thread.start()在你的main()def中。

import threading 

class ThreadClass(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 

    def run(self): 
     global a 
     a = 'Test' 
    def main(self): 
     thread = ThreadClass() 
     thread.start() 

a= 'funny' 
print a 

ThreadClass().main() 
print a 


>>>funny 
>>>Test 
+0

借用示例[from here ](http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-c​​reated-them) – EoinS

+0

'run'被穿線機器調用。 –

+0

需要啓動()線程 – EoinS

0

嘗試從代碼中取出兩句話:

global AUTHEN;