python - 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!
解决方案
推荐阅读
- python - 无法注销用户 django 身份验证
- r - 通过标题和图表在 knitr 中循环
- android - android build failed gradle 无法解决
- c# - ItemsControl 不更新 ItemsSource 绑定
- python - 插入 heapq 是否比插入 bisect 快?
- apache-kafka - Confluent Kafka GCS(Google Cloud Storage)连接器在加载属性文件时出现解析错误
- python - How to print a list of dicts as an aligned table?
- r - 将列添加到 R data.table 并使用用户定义的函数聚合,将输出作为向量返回
- c# - 绑定数据 Xamarin 表单
- ios - 当 iPhone 处于单应用模式时,在应用内安装内部应用