sys.stdout을 로그 파일에 복제
sys.stdout을 로그 파일에 복제하면 시스템 호출을 포함한 모든 출력을 캡처할 수 있습니다. , Python 애플리케이션에서. 단순함에도 불구하고 이 작업은 애플리케이션이 대화형 모드와 데몬 모드 모두에서 작동할 때 독특한 과제를 제기합니다.
대화형 대 데몬 모드
대화형 모드에서는 다음을 원합니다. 화면과 로그 파일 모두 출력을 수신합니다. 그러나 데몬 모드에서는 모든 출력이 로그 파일로 전달되어야 합니다. os.dup2() 함수는 데몬 모드에서 출력을 리디렉션하는 데 적합하지만 시스템 호출을 수정하지 않고 대화형 모드에서 출력을 복제하는 간단한 솔루션을 제공하지 않습니다.
Tee를 사용한 복제
이 문제를 극복하려면 stdout을 로그 파일에 복제하는 방법을 제공하는 Tee 클래스를 사용할 수 있습니다. 예는 다음과 같습니다.
class Tee(object): def __init__(self, name, mode): self.file = open(name, mode) self.stdout = sys.stdout sys.stdout = self def __del__(self): sys.stdout = self.stdout self.file.close() def write(self, data): self.file.write(data) self.stdout.write(data) def flush(self): self.file.flush()
이 클래스를 사용하면 로그 파일 이름과 모드를 매개변수로 사용하는 Tee 인스턴스를 생성할 수 있습니다. write() 메소드는 로그 파일과 stdout 모두에 출력을 복제합니다.
구현 예
Tee 클래스를 사용하려면:
with Tee('logfile.txt', 'w') as tee: print('Hello world!') os.system('ls -la')
이 예에서는 'ls -la'에 대한 시스템 호출을 포함한 모든 출력이 화면과 로그 파일 모두에 기록됩니다. 'logfile.txt'.
이 솔루션은 개별 시스템 호출을 수정할 필요 없이 시스템 호출 출력을 포함한 모든 출력을 효과적으로 기록합니다.
위 내용은 대화형 모드와 데몬 모드 모두에서 Python의 sys.stdout을 로그 파일에 어떻게 복제할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

Dreamweaver Mac版
시각적 웹 개발 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경
