【问题标题】:Using Python in Windows - 'sys.stdin' error在 Windows 中使用 Python - 'sys.stdin' 错误
【发布时间】:2017-06-15 23:22:04
【问题描述】:

为了让聊天系统在 Python 中使用 Windows 工作,我在客户端使用了以下代码:

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, '试图对某事物进行操作 不是套接字')

这与sys.stdin有关。

我认为这是 Windows 上的文件对象不可接受的问题,但套接字可以。在 Windows 上,底层选择函数由 WinSock 库提供,并且不处理并非源自 WinSock 的文件描述符。

是否有解决方法以允许在 Windows 上实现 chat_client.py 代码?

【问题讨论】:

  • ...不要尝试像使用套接字一样使用标准输入?不知道你在这里期待什么样的答案。
  • 有很多方法可以实现“不要那样做”的方法。一个是多线程——如果你有一个从标准输入读取的单独线程,它可以做简单的事情并使用阻塞读取调用,而你的网络代码使用select()recv()(后者同样是一个套接字调用预计不会与标准输入一起使用)。
  • 很多现有的问题都重叠了。参见例如 stackoverflow.com/questions/10842428/…stackoverflow.com/questions/12499523/…
  • 感谢您的 cmets 查尔斯。我正在尝试按照本指南制作聊天应用程序:bogotobogo.com/python/… 我之前使用过多线程,并且我已经查看了您列出的问题,但是我无法获得明确的解决方案。跨度>

标签: python windows python-2.7 sockets cmd


【解决方案1】:

是否有解决方法以允许一种方法来实现 chat_client.py Windows 上的代码?

您可以通过定期检查输入活动来进行管理,例如。 G。通过将您的 select 语句替换为

        # 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)

请注意,在此示例方法中,当您开始输入一行时,只有在输入行完成后才会显示传入的消息。

【讨论】:

    猜你喜欢
    • 2013-11-17
    • 2012-09-12
    • 2013-04-23
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2016-04-25
    相关资源
    最近更新 更多