다중 처리의 로그 출력. 프로세스
파이썬에서 multiprocessing.Process 클래스를 사용할 때 주어진 Process의 stdout 출력을 기록하는 방법이 있습니까?
가장 쉬운 방법은 sys.stdout
. 다중 처리 매뉴얼 의 예를 약간 수정 :
from multiprocessing import Process
import os
import sys
def info(title):
print title
print 'module name:', __name__
print 'parent process:', os.getppid()
print 'process id:', os.getpid()
def f(name):
sys.stdout = open(str(os.getpid()) + ".out", "w")
info('function f')
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
q = Process(target=f, args=('fred',))
q.start()
p.join()
q.join()
그리고 실행 :
$ ls m.py $ 파이썬 m.py $ ls 27493.out 27494.out m.py $ 고양이 27493.out 기능 f 모듈 이름 : __main__ 부모 프로세스 : 27492 프로세스 ID : 27493 안녕 밥 $ 고양이 27494.out 기능 f 모듈 이름 : __main__ 부모 프로세스 : 27492 프로세스 ID : 27494 안녕 프레드
@Mark Rushakoff 답변에 추가 할 것은 두 가지뿐입니다. 디버깅 할 때 호출 buffering
매개 변수 open()
를 0 으로 변경하는 것이 정말 유용하다는 것을 알았습니다 .
sys.stdout = open(str(os.getpid()) + ".out", "a", buffering=0)
그렇지 않으면 madnesstail -f
. 출력 파일을 보낼 때 결과가 간헐적으로 발생할 수 있기 때문 입니다. buffering=0
에 대한 tail -f
중대한을 보내고.
그리고 완전성을 위해 자신에게 호의를 베풀고 리디렉션하십시오 sys.stderr
.
sys.stderr = open(str(os.getpid()) + "_error.out", "a", buffering=0)
또한 편의를 위해 원하는 경우 별도의 프로세스 클래스에 덤프 할 수 있습니다.
class MyProc(Process):
def run(self):
# Define the logging in run(), MyProc's entry function when it is .start()-ed
# p = MyProc()
# p.start()
self.initialize_logging()
print 'Now output is captured.'
# Now do stuff...
def initialize_logging(self):
sys.stdout = open(str(os.getpid()) + ".out", "a", buffering=0)
sys.stderr = open(str(os.getpid()) + "_error.out", "a", buffering=0)
print 'stdout initialized'
메서드 (즉시 또는 a 가 감지 될 때까지 누적 )가 호출 (또는 로그하려는 다른 방법 )을 갖는 클래스의 sys.stdout = Logger()
위치 를 설정할 수 있습니다 . 이 행동의 예.Logger
write
\n
logging.info
I'm not sure what you mean by "a given" process (who's given it, what distinguishes it from all others...?), but if you mean you know what process you want to single out that way at the time you instantiate it, then you could wrap its target
function (and that only) -- or the run
method you're overriding in a Process
subclass -- into a wrapper that performs this sys.stdout "redirection" -- and leave other processes alone.
Maybe if you nail down the specs a bit I can help in more detail...?
참고URL : https://stackoverflow.com/questions/1501651/log-output-of-multiprocessing-process
'Nice programing' 카테고리의 다른 글
R로 압축하거나 열거 하시겠습니까? (0) | 2020.11.18 |
---|---|
캐싱이란 무엇입니까? (0) | 2020.11.18 |
Android : 스크롤이 언제 끝났는지 감지하는 방법 (0) | 2020.11.18 |
VMWare 플레이어 대 VMWare 워크 스테이션 (0) | 2020.11.18 |
ArrayList에 개체를 추가하고 나중에 수정 (0) | 2020.11.18 |