python - python中的原始输入和多处理

标签 python raw-input

我有(主要)以下代码:

status = raw_input("Host? (Y/N) ") 
if status=="Y":
    print("host")
    serverprozess = Process(target= spawn_server)
    serverprozess.start()
clientprozess = Process (target = spawn_client)
clientprozess.start()

上面调用的方法基本上是这样的:

def spawn_server():
     mserver = server.Gameserver()
    #a process for the host. spawned if and only if the player acts as host

def spawn_client():
    myClient = client.Client()
    #and a process for the client. this is spawned regardless of the player's status

它工作正常,服务器生成,客户端也生成。

就在昨天,我在 client.Client() 中添加了以下行:

self.ip = raw_input("IP-Adress: ") 

第二个 raw_input 抛出 EOF 异常:

     ret = original_raw_input(prompt)
     EOFError: EOF when reading a line

有办法解决这个问题吗?我不能使用多个提示吗?

最佳答案

正如您已经确定的那样,最简单的方法是仅从主进程调用 raw_input:

status = raw_input("Host? (Y/N) ") 
if status=="Y":
    print("host")
    serverprozess = Process(target= spawn_server)
    serverprozess.start()

ip = raw_input("IP-Address: ")     
clientprozess = Process (target = spawn_client, args = (ip, ))
clientprozess.start()

但是,使用 J.F. Sebastian's solution也可以复制 sys.stdin 并将其作为参数传递给子进程:

import os
import multiprocessing as mp
import sys

def foo(stdin):
    print 'Foo: ',
    status = stdin.readline()
    # You could use raw_input instead of stdin.readline, but 
    # using raw_input will cause an error if you call it in more 
    # than one subprocess, while `stdin.readline` does not 
    # cause an error.
    print('Received: {}'.format(status))

status = raw_input('Host? (Y/N) ')
print(status)
newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
try:
    proc1 = mp.Process(target = foo, args = (newstdin, ))
    proc1.start()
    proc1.join()
finally:
    newstdin.close()

关于python - python中的原始输入和多处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13786974/

相关文章:

python - 如何在 Python 中获取多个多行输入变量?

Python raw_input 忽略换行符

java - 身份验证方法

python - 如何从列表 Python 创建带有下划线的子集列表

python - 在 Jinja Render 方法中使用变量作为键

c++ - GetKeyNameText 小键盘缺少文本

c# - 带有 WPF 的 SlimDX RawInput

python - 如何为 raw_input 设置默认的可编辑字符串?

python - Numpy 数组维度的选择

python - 具有 3 列的 DataFrame 到字典的字典