使子进程保持活动状态,并不断向其发出命令python 3

使子进程保持活动状态,并不断向其发出命令python 3,python,python-3.x,subprocess,Python,Python 3.x,Subprocess,已接受答案中的代码在python 3.6中不起作用(它只是挂起)。有办法解决吗 from subprocess import Popen, PIPE # Run "cat", which is a simple Linux program that prints it's input. process = Popen(['/bin/cat'], stdin=PIPE, stdout=PIPE, encoding='utf-8', universal_newlines=True) process

已接受答案中的代码在python 3.6中不起作用(它只是挂起)。有办法解决吗

from subprocess import Popen, PIPE

# Run "cat", which is a simple Linux program that prints it's input.
process = Popen(['/bin/cat'], stdin=PIPE, stdout=PIPE, encoding='utf-8', universal_newlines=True)
process.stdin.write('Hello\n')
print(repr(process.stdout.readline())) # Should print 'Hello\n'
process.stdin.write(b'World\n')
print(repr(process.stdout.readline())) # Should print 'World\n'

# "cat" will exit when you close stdin.  (Not all programs do this!)
process.stdin.close()
print('Waiting for cat to exit')
process.wait()
print('cat finished with return code %d' % process.returncode)
在Python 3.6(以及据我所知的其他版本)中,process.stdin.write接受字节对象,而不是字符串

process.stdin.write(b'Hello\n')

编辑:编辑问题后,此答案无效。(它向Popen构造函数添加了一个编码。)

根据@DanielPryden的建议,您需要显式刷新stdin:

from subprocess import Popen, PIPE

# Run "cat", which is a simple Linux program that prints it's input.
process = Popen(['/bin/cat'], stdin=PIPE, stdout=PIPE)
process.stdin.write(b'Hello\n')
process.stdin.flush()
print(repr(process.stdout.readline())) # Should print 'Hello\n'
process.stdin.write(b'World\n')
process.stdin.flush()
print(repr(process.stdout.readline())) # Should print 'World\n'

# "cat" will exit when you close stdin.  (Not all programs do this!)
process.stdin.close()
print('Waiting for cat to exit')
process.wait()
print('cat finished with return code %d' % process.returncode)

cat
和您的程序之间是一个缓冲区,很可能在Python端的libc stdio实现中。您需要刷新此缓冲区,以确保
cat
已看到您写入的字节,然后将进程置于休眠状态,等待
cat
写回一些字节


可以通过调用
process.stdin.flush()
显式执行此操作,也可以通过禁用缓冲区隐式执行此操作。我认为这里的显式形式可能更好:它简单且明确正确

挂在哪里?你在运行什么操作系统?你能确认
cat
确实在执行吗?另外:如果这段代码在Python2.x上运行,在3.x上失败,我会假设这是字节对unicode的问题。尝试在
Popen
构造函数中指定
encoding='utf-8'
。哦,如果您使用的是非Unix操作系统,那么您肯定也需要在
Popen
构造函数中指定
universal\u newlines=True
。mac OS 10.12 Anaconda python 2.7挂在readline上。不幸的是,添加编码没有帮助,universal_Newlines也没有。实际上,这对我来说是打印
5
,所以我可能错了。真的吗?我得到
TypeError:process.stdin.write('test\n')
上需要一个类似字节的对象,而不是'str'。这在IDLE 3.6.2中。您确定运行的是python 3吗?如果您设置了编码,它将使用Unicode字符串,否则将使用bytestring。@OldBunny2800:使用
Popen
构造函数的
encoding
参数。有关详细信息,请使用
帮助(subprocess.Popen)