Python 用subprocess.Popen修饰CLI程序

Python 用subprocess.Popen修饰CLI程序,python,subprocess,command-line-interface,stdout,stdin,Python,Subprocess,Command Line Interface,Stdout,Stdin,我想装饰python.exe。例如,当我们写入stdin时,它可以是输入:\n;当我们在交互模式下读取stdout前缀时,它可以是输出:\n: 原始python.exe: $ python Python 3.6.1 |Anaconda custom (64-bit)| (default, Mar 22 2017, 20:11:04) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "licen

我想装饰
python.exe
。例如,当我们写入
stdin
时,它可以是
输入:\n
;当我们在交互模式下读取
stdout
前缀时,它可以是
输出:\n

原始
python.exe

$ python
Python 3.6.1 |Anaconda custom (64-bit)| (default, Mar 22 2017, 20:11:04) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(2)
2
>>> 2 + 2
4
>>>
$ decorated_python
Output:
Python 3.6.1 |Anaconda custom (64-bit)| (default, Mar 22 2017, 20:11:04) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Input:
print(2)
Output:
2
>>> 
Input:
2 + 2
Output:
4
>>>
例外装饰
python.exe

$ python
Python 3.6.1 |Anaconda custom (64-bit)| (default, Mar 22 2017, 20:11:04) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(2)
2
>>> 2 + 2
4
>>>
$ decorated_python
Output:
Python 3.6.1 |Anaconda custom (64-bit)| (default, Mar 22 2017, 20:11:04) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Input:
print(2)
Output:
2
>>> 
Input:
2 + 2
Output:
4
>>>
我认为应该是这样的:

import subprocess

pid = subprocess.Popen("python".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while True:
    pid.stdin.write(input('Input:\n').encode())
    print('Output:\n' + pid.stdout.readlines())
但是
pid.stdout.readlines()
从未完成

我也尝试过使用
沟通
方法,但它只在第一次起作用:

import subprocess

pid = subprocess.Popen("python".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while True:
    print('Output:\n', pid.communicate(input('Input:\n').encode()))
测试:

装饰有
沟通
方法:

Input:
2
Output:
 (b'', b'')

如果您查看python文档,您会发现在使用stdin/stdout=PIPE时,不建议在这些流上使用读/写操作,因为这可能会导致死锁—您在执行读线时实际会遇到这种情况:

下一个问题就要解决了

“Popen.communicate()是一个助手方法,它将数据一次性写入stdin,并创建线程从stdout和stderr中提取数据。它在完成数据写入后关闭stdin,并读取stdout和stderr,直到这些管道关闭。您无法进行第二次通信,因为在返回时子级已经退出。”@tdelaney

更多信息,请访问:

一般来说,做交互式子进程比较困难,您可以尝试使用