我想装饰python.exe
。例如,它可以只是Input:\n
当我们写信给stdin
和Output:\n
当我们从stdout
前缀在交互模式下阅读:用子进程装饰CLI程序.Popen
原始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
>>>
除外装饰python.exe
:
$ 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()
没做过。
我还试图用communicate
方法,但它的工作只是第一次:
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:
print(1)
Output:
(b'1\r\n', b'')
Input:
pritn(1)
Traceback (most recent call last):
File "C:/Users/adr-0/OneDrive/Projects/Python/AdrianD/temp/tmp.py", line 6, in <module>
print('Output:\n', pid.communicate(input('Input:\n').encode()))
File "C:\Users\adr-0\Anaconda3.6\lib\subprocess.py", line 811, in communicate
raise ValueError("Cannot send input after starting communication")
ValueError: Cannot send input after starting communication
也许我只是错过的东西,因为如果我把刚刚2
在python
我会得到2
。但我不能得到这个2
与communicate
方法:
纯Python:
>>> 2
2
与communicate
方法装饰:
Input:
2
Output:
(b'', b'')
感谢您的回答。但不幸的是'pexpect'在Windows上不起作用... – ADR