我想裝飾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