2017-10-15 7 views
0

장식하고 싶습니다. python.exe. 예를 들어, 할 수 있습니다 단지 Input:\n 우리가 대화 형 모드에서 stdout 접두사에서 읽을 때 우리는 stdinOutput:\n 쓸 때하위 프로세스가있는 CLI 프로그램을 장식합니다. 팝업

원래 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())) 

테스트 : 난 그냥 2python에서 나는 것 세우면 때문에

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을 얻으십시오. 당신은 파이썬 문서를 보면

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

답변

1

당신이 표준 입력을 사용할 때 찾을 수 있습니다

순수 파이썬 : communicate 방법으로 장식

>>> 2 
2 

하지만 communicate 방법이 2를 얻을 수 없다/stdout = PIPE 스트림에서는 읽기/쓰기 작업을 사용하지 않는 것이 좋습니다. 실제로는 readline을 수행하는 동안 경험 한 교착 상태가 발생할 수 있습니다. https://docs.python.org/2/library/subprocess.html#popen-objects

다음 문제 때문

"Popen.communicate()는 표준 입력 데이터의 한번 쓰기를 수행하고 표준 출력과 표준 에러 데이터를 가져와 스레드를 생성하는 헬퍼 메소드이다. 그것은 데이터 쓰기가 완료되면 stdin을 닫고 파이프가 닫힐 때까지 stdout 및 stderr를 읽습니다. 아이는 이미 반환 시간 종료했기 때문에 두 번째 의사 소통을 할 수 없다 "@tdelaney

에서

더 :. Multiple inputs and outputs in python subprocess communicate

은 일반적으로 상호 작용하는 자식 프로세스가 어려운 일을, 당신이 를 사용하려고 할 수 있습니다 https://pexpect.readthedocs.io/en/stable/

+0

답변 해 주셔서 감사합니다.하지만 불행히도'pexpect'는 Windows에서 작동하지 않습니다 ... – ADR