【发布时间】:2026-02-05 04:30:01
【问题描述】:
我想装饰python.exe。例如,当我们在交互模式下写入 stdin 和从 stdout 前缀读取时,它可能只是 Input:\n 和 Output:\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
>>>
除装饰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。但是我不能用communicate方法得到这个2:
纯蟒蛇:
>>> 2
2
用communicate方法装饰:
Input:
2
Output:
(b'', b'')
【问题讨论】:
标签: python subprocess command-line-interface stdout stdin