gpt4 book ai didi

python - 这个多处理 python 脚本有什么问题?

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:23 25 4
gpt4 key购买 nike

我正在编写一个可在终端上运行的简单消息传递程序(适用于 2 个用户)。

为了实现它,我决定创建 2 个进程,一个用于服务器(等待来自其他用户的消息到达),另一个用于客户端(只是将消息发送到其他用户的服务器进程) )

事实是,当我运行它时,出现以下错误:

C:\>python message.py

> Process Process-2:
Traceback (most recent call last):
File "C:\Python27\lib\multiprocessing\process.py", line 258, in_bootstrap
self.run()
File "C:\Python27\lib\multiprocessing\process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "C:\message.py", line 12, in send_messages
message = raw_input('> ')
EOFError

Process Process-1:
Traceback (most recent call last):
File "C:\Python27\lib\multiprocessing\process.py", line 258, in
_bootstrap
self.run()
File "C:\Python27\lib\multiprocessing\process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "C:\message.py", line 25, in receive_messages
message = sc.recv(1024)
error: [Errno 10054] An existing connection was forcibly closed by the
remote host

这是我的 Python 代码

from multiprocessing import Process
import socket

direction = "localhost"

global s
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
def send_messages():
s.connect((direction, 5124))
while True:
message = raw_input('> ')
s.send(message)
if message == 'close':
break
print 'Bye'
s.close()

def receive_messages():
s.bind(("localhost",5124))
s.listen(2)
sc, addr = s.accept()

while True:
message = sc.recv(1024)
print message
sc.close()
s.close()

if __name__ == '__main__':

p1 = Process(target = receive_messages)
p1.start()
p2 = Process(target = send_messages)
p2.start()
p1.join()
p2.join()

注意 1:由于从我的文本编辑器剪切和粘贴到 stackoverflow,可能会出现一些缩进错误。

注意 2:我在 Windows 10 上工作

最佳答案

来自 the documentation :

Beware of replacing sys.stdin with a “file like object”

multiprocessing originally unconditionally called:

os.close(sys.stdin.fileno())

in the multiprocessing.Process._bootstrap() method — this resulted in issues with processes-in-processes. This has been changed to:

sys.stdin.close()
sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)

Which solves the fundamental issue of processes colliding with each other resulting in a bad file descriptor error, but introduces a potential danger to applications which replace sys.stdin() with a “file-like object” with output buffering. This danger is that if multiple processes call close() on this file-like object, it could result in the same data being flushed to the object multiple times, resulting in corruption.

底线是您的 Processes 正在关闭 stdin 除非您对它们进行子类化并避免这样做。

您可能会考虑使用一个(大写-P)进程来处理通信,然后在您的原始(小写)进程中进行输入/输出:

if __name__ == '__main__':

p1 = Process(target = receive_messages)
p1.start()

send_messages()

p1.join()

关于python - 这个多处理 python 脚本有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43404466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com