2017-10-15 134 views
0

我想装饰python.exe。例如,它可以只是Input:\n当我们写信给stdinOutput:\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 

也许我只是错过的东西,因为如果我把刚刚2python我会得到2。但我不能得到这个2communicate方法:

纯Python:

>>> 2 
2 

communicate方法装饰:

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

回答

1

如果你看一下Python文档,你可以找到使用标准输入时/ stdout = PIPE几乎不建议不要在这些流上使用读/写操作,因为这会导致死锁 - 您在执行readlines时实际遇到的问题: https://docs.python.org/2/library/subprocess.html#popen-objects

接下来的问题是由于

“Popen.communicate()是一个辅助方法,做数据的一次性写入到stdin和创建线程从stdout和stderr拉数据。它完成写入数据并关闭标准输入,并读取stdout和stderr,直到这些管道关闭。你不能做第二次沟通,因为孩子已经返回的时候已经退出“@tdelaney

更多: Multiple inputs and outputs in python subprocess communicate

一般是在做交互子过程很辛苦,你可以尝试使用 https://pexpect.readthedocs.io/en/stable/

+0

感谢您的回答。但不幸的是'pexpect'在Windows上不起作用... – ADR