2017-10-15 132 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