推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
sbldehanhan
V2EX  ›  Python

奇了怪了? 26 行的 input 函数在 Linux 上为啥不阻塞啊?在 Windows 上是阻塞的?

  •  
  •   sbldehanhan · Aug 15, 2023 · 1917 views
    This topic created in 1136 days ago, the information mentioned may be changed or developed.

    import socket #创建服务端的 socket 对象 socketserver socketserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '192.168.0.103' port = 4567 #绑定地址(包括 ip 地址会端口号) socketserver.bind((host, port)) #设置监听 socketserver.listen(5) #等待客户端的连接 #注意:accept()函数会返回一个元组 #元素 1 为客户端的 socket 对象,元素 2 为客户端的地址(ip 地址,端口号) clientsocket,addr = socketserver.accept()

    #while 循环是为了能让对话一直进行,直到客户端输入 q while True:

    #接收客户端的请求
    recvmsg = clientsocket.recv(1024)
    #把接收到的数据进行解码
    strData = recvmsg.decode("utf-8")
    #判断客户端是否发送 q ,是就退出此次对话
    if strData=='q':
        break
    print("收到:"+strData)
    msg = input("回复:")
    #对要发送的数据进行编码
    clientsocket.send(msg.encode("utf-8"))
    
    gdcbhtd
        1
    gdcbhtd  
       Aug 15, 2023
    好像是在 Windows 上,input 函数会阻塞代码的执行,直到用户输入回车键,并返回用户输入的内容。而在 Linux 上,input 函数默认情况下是非阻塞的,它会立即返回一个空字符串,不会等待用户输入。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2302 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 00:51 · PVG 08:51 · LAX 17:51 · JFK 20:51
    ♥ Do have faith in what you're doing.