2017-05-19 8 views
-1
with open('WarningErr.txt', 'w') as err: 
    subprocess.call(cmd, stderr=err) 

with open('WarningOut.txt', 'w') as out: 
    return_code = subprocess.call(cmd, stdout=out) 

지금은 둘 다 오류를 작성하고 ".txt 및 stdout"으로 출력합니다.Python - 파일과 콘솔을 동시에 작성하는 방법 (Bash 파일에서)

하지만 너무 느립니다. 나는 하나에서, 그리고 다른 하나에서 글을 쓴다. 나는 동시에 둘 다 쓸 수 있어야합니다.

Bash에서 티 (tee) 동작을 약간 복제합니다.

+0

'subprocess'를 통해 호출하는 명령에'tee'를 포함시키지 않으시겠습니까? –

+0

이것은 당신에게 유용 할 수 있습니다 : [평범한 것처럼 파이썬 서브 프로세스 출력을 stdout과 stderr로 출력 할 수 있습니까? \ [duplicate \]] (http://stackoverflow.com/q/12270645/953482) – Kevin

+0

감사합니다. 그러나 서브 프로세스 호출 @Rightleg에서 매우 잘 작동했습니다. –

답변

0

@Rightleg와 같은 명령 호출에 tee가 포함되었습니다. 명령을 변경합니다. 하지만 지금은 완벽하게 작동합니다.

하위 프로세스를 통해 tee를 호출 할 수 있다고 생각하지 않았습니다. 하지만 실제로 잘 작동합니다!

# for example 
command = 'ls' 

# To write at the same time in the shell and a file both errors, and stdout (TEE behaviour) 
cmd = ['bash', '-c', '. myBash.bash; {} > >(tee {}/WarningOut.txt) 2> >(tee {}/WarningErr.txt >&2)' 
     .format(command, PATHTOWHEREYOUWANTIT_g, PATHTOWHEREYOUWANTIT_g)] 

return_code = subprocess.call(cmd) 
+0

최종 코드를 추가하여 다른 사람에게 도움이 될 수 있습니까? 사용자? :) –

0

stdout/stderr 및 파일에 기록하고 싶습니다. 로깅 라이브러리와 다음 코드를 시도하십시오 :

import logging 

# create logger obj 
_glogger = logging.getLogger("myApp") 

# create file sink 
hdlr = logging.FileHandler(os.path.join("dumpDir",'myApp.log')) 
formatter = logging.Formatter('%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s') 
hdlr.setFormatter(formatter) 
_glogger.addHandler(hdlr) 

# create steam sink = stdout 
hdlr2 = logging.StreamHandler() 
hdlr2.setFormatter(formatter) 
_glogger.addHandler(hdlr2) 
_glogger.setLevel(logging.DEBUG) 

_glogger.debug("a debug message") 
+0

예, 결국 시도해야 할 것이 있습니다. –