首页 > 解决方案 > python - 接受用户输入,同时输出字符串

问题描述

在大多数控制台和 IRC 应用程序中,用户可以在控制台进行输出的同时进行输入。这在python中可能吗?如果是这样,如何?我正在尝试制作一个类似 IRC 的应用程序,并且尝试一次使用多个线程,但输入从未完全注册。为了测试目的,我让服务器每隔几秒钟重复一条消息。

这是客户端的代码:

import socket
import threading

TARGET_IP = socket.gethostname()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create socket object using IPV4 and TCP respectively

def utf8len(a):
    return len(a.encode('utf-8')) #returns length of string in unicode

def recievethread():
    while True:
        full_msg = ''
        msg = s.recv(1024) #waits to recieve message
        full_msg += msg.decode("utf-8") #decode
        print(full_msg) #print
        
def inputthread():
    while True: #input loop
        inp = input()
        print("[DEBUG] - {inp}")
        if inp == "!04exit":
            recieving.exit()
            print("[CLIENT] - Closing connection to {TARGET_IP}!")
            break #safely close the client with all threads
        
        if utf8len(inp) < 1024:
            pass
        else:
            print("[CLIENT] - message is too long!")

s.connect((TARGET_IP, 1432)) #establish connection on the same machine for now

recieving = threading.Thread(target=recievethread)
recieving.start()
inputloop = threading.Thread(target=inputthread)
inputloop.start()

这就是我在服务器运行时尝试输入时发生的情况:

$ python client.py                                                
Welcome to the Server!
This is a timed message!
Trying This is a timed message!
to type This is a timed message!
an This is a timed message!
input wiThis is a timed message!
thoutThis is a timed message!
 pressing enThis is a timed message!
ter
Exception in thread Thread-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "client.py", line 30, in inputthread
    inp = input()
  File "<string>", line 1
    Trying to type an input without pressing enter
            ^
SyntaxError: invalid syntax

This is a timed message!
This is a timed message!

标签: pythonsocketspython-multithreading

解决方案


推荐阅读