2012-12-09 66 views
2

我(主)下面的代码:原始输入和多在python

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 

它正常工作,服务器产卵客户也是如此。

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

第二抛出的raw_input的EOF -exception:

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

有没有办法解决这个问题只有

昨天我在client.Client()以下行添加?我可以不使用多个提示吗?

+0

也就是说,我甚至没有要求原始输入,行甚至没有打印。 – user1862770

+0

我通过将raw_input放在main中解决了这个问题。 – user1862770

+0

但是现在有某事别人我百思不得其解:IP的raw_input =( “IP-地址:”) 打印(IP) clientprozess =过程(目标= spawn_client,ARGS = IP) clientprozess.start() – user1862770

回答

4

正如你已经确定,这是最简单的调用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()