2016-10-24 2 views
3

안녕하세요, 저는 파이썬에 초보자입니다. stderr이 check_output 서브 프로세스와 어떻게 사용되는지 이해하려고합니다. 하위 프로세스 문서를 읽었으며 stderr가 어떻게 사용되고 어떤 구체적으로 subprocess.STDOUT이 실제로 수행하는지 이해하는 데 어려움이 있습니다.Python subprocess.check_output stderr usage

stderr가 여기에 사용되는 방법을 설명하는 몇 가지 예 또는 참고 자료에 대한 도움을 얻을 수 있습니까?

나는이 명령을 stderr와 without를 사용하여 시도했지만 실제 차이점은 발견하지 못했다.

코드 :

#!/usr/bin/python3 
import subprocess 

print(subprocess.check_output("echo Hello World!", 
           stderr=subprocess.STDOUT, 
           shell=True)) 

출력 :

# ./ex.py 
b'Hello World!\n' 

코드 :

#!/usr/bin/python3 
import subprocess 

print(subprocess.check_output("gecho Hello World!", 
           stderr=subprocess.STDOUT, 
           shell=True)) 

출력 :

# ./ex.py 
Traceback (most recent call last): 
    File "./ex.py", line 6, in <module> 
    shell=True)) 
    File "/usr/lib64/python3.3/subprocess.py", line 589, in check_output 
    raise CalledProcessError(retcode, process.args, output=output) 
subprocess.CalledProcessError: Command 'gecho Hello World!' returned non-zero exit status 127 
+0

리턴 코드가 0이 아니기 때문에 * CalledProcessError *가 발생합니다. 모든 stderr = subprocess.STDOUT은 * stderr을 * stdout *로 리디렉션합니다. 파이썬 코드에서 오류를 포착하는 것과 아무런 관련이 없습니다. stderr를 표준 출력으로 리다이렉트하지 않으면 stderr에서 출력 된 모든 것이 화면에 출력되고 check_output에 의해 캡쳐되지 않습니다. 이것은 stderr = subprocess.STDOUT http://stackoverflow.com/questions/을 사용하고자 할 때의 예입니다. 39917569/why-doesnt-this-regex-work/39917623 # 39917623. –

+0

@PadraicCunningham stderr로 보내지는 내용이나 stdout으로 리디렉션 된 내용을 어떻게 읽을 수 있습니까? 그것을 표준 출력으로 리디렉션해야 할 필요성은 무엇입니까? 감사합니다 – MBasith

+0

당신이 stdout 대신 stderr을 파이프하는 프로세스가 출력을 캡처하고 싶다면 어떻게해야할까요? 위의 링크에서 정확히 일어난 일을 볼 수 있습니다. –

답변

1

subprocess.check_output은 종료 코드가 0이 아닌 경우 표시되는 예외를 발생시킵니다. 당신이 얻을려고하는 경우에 쉬운 일이 subprocess.run 및 파이프 STDOUT 및 STDERR을 사용하는 것입니다 STDERR을 읽을 수있는 간단한 방법이있다처럼 소리 (예를 들면 Windows의) :

>>> p = subprocess.run(['cmd','/C','echo','hello','world'], stdout = subprocess.PIPE, stderr=subprocess.PIPE) 
>>> p.stdout 
b'hello world\r\n' 

>>> p.stderr 
b'' 

>>> p = subprocess.run(['cmd','/C','gecho','hello','world'], stdout = subprocess.PIPE, stderr=subprocess.PIPE) 
>>> p.stdout 
b'' 

>>> p.stderr 
b"'gecho' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" 
당신은 정말 check_output를 사용해야하는 경우

, 다음은 에코 호출에서 오류 코드를 무시하고 계속 (워드 프로세서에서 거의 그대로 촬영 예) 오류 출력합니다 :

>>> print(subprocess.check_output('gecho hello& exit 0', stderr=subprocess.STDOUT, shell=True)) 
b"'gecho' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n" 

또는 리눅스 :

>>> print(subprocess.check_output('gecho hello; exit 0', stderr=subprocess.STDOUT, shell=True)) 
b'/bin/sh: 1: gecho: not found\n' 

부수적으로, 거의 shell = True 옵션으로 하위 프로세스 기능을 사용하는 것이 좋습니다. 주로 보안 문제 때문입니다. 전체 설명을 보려면 문서를 읽으십시오.