2017-01-30 71 views
0

在試圖獲得聊天系統使用的是Windows在Python的工作,我已經使用了下面的代碼在客戶端:在Windows中使用Python - 「sys.stdin」錯誤

chat_client.py

import sys, socket, select 

def chat_client(): 
    if(len(sys.argv) < 3) : 
     print 'Usage : python chat_client.py hostname port' 
     sys.exit() 

    host = sys.argv[1] 
    port = int(sys.argv[2]) 

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    s.settimeout(2) 

    # connect to remote host 
    try : 
     s.connect((host, port)) 
    except : 
     print 'Unable to connect' 
     sys.exit() 

    print 'Connected to remote host. You can start sending messages' 
    sys.stdout.write('[Me] '); sys.stdout.flush() 

    while 1: 
     socket_list = [sys.stdin, s] 

     # Get the list sockets which are readable 
     read_sockets, write_sockets, error_sockets = select.select(socket_list , [], []) 

     for sock in read_sockets:    
      if sock == s: 
       # incoming message from remote server, s 
       data = sock.recv(4096) 
       if not data : 
        print '\nDisconnected from chat server' 
        sys.exit() 
       else : 
        #print data 
        sys.stdout.write(data) 
        sys.stdout.write('[Me] '); sys.stdout.flush()  

      else : 
       # user entered a message 
       msg = sys.stdin.readline() 
       s.send(msg) 
       sys.stdout.write('[Me] '); sys.stdout.flush() 

if __name__ == "__main__": 

    sys.exit(chat_client()) 

但是,我得到嘗試連接到服務器時出現以下錯誤(這是在Python運行過):

select.error: (10038, 'An operation was attempted on something that is not a socket')

這有事情做與sys.stdin

我相信這是Windows上的文件對象不可接受的問題,但套接字是。在Windows上,底層選擇函數由WinSock庫提供,並且不處理源自WinSock的文件描述符。

有沒有解決方法,以允許在Windows上實現chat_client.py代碼的方法?

+0

...不要嘗試使用stdin,就好像它是一個套接字?不知道你在這裏期待什麼樣的答案。 –

+0

很多方法來實現「不這樣做」的方法。一個是多線程 - 如果你有一個單獨的線程讀取stdin,它可以做到簡單的事情,並使用阻塞讀取調用,而你的網絡代碼使用'select()'和'recv()'(後者是同樣一個套接字調用不會與標準輸入工作)。 –

+0

這個重疊的問題很多。看例如http://stackoverflow.com/questions/10842428/can-select-be-used-with-files-in-python-under-windows和http://stackoverflow.com/questions/12499523/using-sys -stdin-in-select-select-on-windows?rq = 1 –

回答

0

Is there a workaround to this to allow for a way to implement the chat_client.py code on Windows?

您可以定期檢查輸入活動,例如, G。通過

 # Get the list sockets which are readable, time-out after 1 s 
     read_sockets = select.select([s], [], [], 1)[0] 
     import msvcrt 
     if msvcrt.kbhit(): read_sockets.append(sys.stdin) 

注意,在這個例子中的做法,當一個人開始在一個行中輸入,輸入的信息只在輸入行結束後顯示更換您select聲明。