파이썬에서 stdout을 "nothing"으로 리디렉션
나는 충분히 많은 수의 모듈로 구성된 큰 프로젝트를 가지고 있으며, 각각은 표준 출력으로 무언가를 인쇄합니다. 이제 프로젝트의 규모가 커짐에 따라 더 큰 프로젝트가 없습니다. 의 print
상당히 느린 프로그램을 만들었습니다 표준 출력에 많이 인쇄 문.
따라서 런타임 에 stdout에 아무것도 인쇄할지 여부 를 결정하려고합니다 . 모듈이 많기 때문에 모듈을 변경할 수 없습니다. (stdout을 파일로 리디렉션 할 수는 있지만 상당히 느립니다.)
그래서 내 질문은 어떻게 stdout을 아무것도로 리디렉션하지 않는 것입니다. 즉, 어떻게 print
진술이 아무것도하지 않게합니까?
# I want to do something like this.
sys.stdout = None # this obviously will give an error as Nonetype object does not have any write method.
현재 내가 가지고있는 유일한 아이디어는 write 메소드 (아무것도하지 않음)가있는 클래스를 만들고 stdout 을이 클래스의 인스턴스로 리디렉션하는 것입니다.
class DontPrint(object):
def write(*args): pass
dp = DontPrint()
sys.stdout = dp
파이썬에 내장 메커니즘이 있습니까? 아니면 이것보다 더 좋은 것이 있습니까?
크로스 플랫폼 :
import os
import sys
f = open(os.devnull, 'w')
sys.stdout = f
Windows에서 :
f = open('nul', 'w')
sys.stdout = f
Linux에서 :
f = open('/dev/null', 'w')
sys.stdout = f
이 작업을 수행하는 좋은 방법은 인쇄물을 감쌀 작은 컨텍스트 프로세서를 만드는 것입니다. 그런 다음-문에 사용 with
하여 모든 출력을 침묵시킵니다.
import os
import sys
from contextlib import contextmanager
@contextmanager
def silence_stdout():
new_target = open(os.devnull, "w")
old_target = sys.stdout
sys.stdout = new_target
try:
yield new_target
finally:
sys.stdout = old_target
with silence_stdout():
print("will not print")
print("this will print")
이 코드를 실행하면 첫 번째 출력이 아닌 두 번째 출력 행만 인쇄됩니다.
$ python test.py
this will print
이것은 크로스 플랫폼 (Windows + Linux + Mac OSX)에서 작동하며 다른 답변보다 깨끗합니다.
python 3.4 이상인 경우 표준 라이브러리를 사용하는 간단하고 안전한 솔루션이 있습니다.
import contextlib
with contextlib.redirect_stdout(None):
print("This won't print!")
(적어도 내 시스템에서는) os.devnull에 쓰는 것이 DontPrint 클래스에 쓰는 것보다 약 5 배 빠릅니다.
#!/usr/bin/python
import os
import sys
import datetime
ITER = 10000000
def printlots(out, it, st="abcdefghijklmnopqrstuvwxyz1234567890"):
temp = sys.stdout
sys.stdout = out
i = 0
start_t = datetime.datetime.now()
while i < it:
print st
i = i+1
end_t = datetime.datetime.now()
sys.stdout = temp
print out, "\n took", end_t - start_t, "for", it, "iterations"
class devnull():
def write(*args):
pass
printlots(open(os.devnull, 'wb'), ITER)
printlots(devnull(), ITER)
gave the following output:
<open file '/dev/null', mode 'wb' at 0x7f2b747044b0>
took 0:00:02.074853 for 10000000 iterations
<__main__.devnull instance at 0x7f2b746bae18>
took 0:00:09.933056 for 10000000 iterations
If you're in a Unix environment (Linux included), you can redirect output to /dev/null
:
python myprogram.py > /dev/null
And for Windows:
python myprogram.py > nul
How about this:
from contextlib import ExitStack, redirect_stdout
import os
with ExitStack() as stack:
if should_hide_output():
null_stream = open(os.devnull, "w")
stack.enter_context(null_stream)
stack.enter_context(redirect_stdout(null_stream))
noisy_function()
This uses the features in the contextlib module to hide the output of whatever command you are trying to run, depending on the result of should_hide_output()
, and then restores the output behavior after that function is done running.
If you want to hide standard error output, then import redirect_stderr
from contextlib
and add a line saying stack.enter_context(redirect_stderr(null_stream))
.
The main downside it that this only works in Python 3.4 and later versions.
Your class will work just fine (with the exception of the write()
method name -- it needs to be called write()
, lowercase). Just make sure you save a copy of sys.stdout
in another variable.
If you're on a *NIX, you can do sys.stdout = open('/dev/null')
, but this is less portable than rolling your own class.
You can just mock it.
import mock
sys.stdout = mock.MagicMock()
Why don't you try this?
sys.stdout.close()
sys.stderr.close()
sys.stdout = None
It is OK for print()
case. But it can cause an error if you call any method of sys.stdout, e.g. sys.stdout.write()
.
There is a note in docs:
Under some conditions stdin, stdout and stderr as well as the original values stdin, stdout and stderr can be None. It is usually the case for Windows GUI apps that aren’t connected to a console and Python apps started with pythonw.
참고URL : https://stackoverflow.com/questions/6735917/redirecting-stdout-to-nothing-in-python
'Programing' 카테고리의 다른 글
ViewController가 모달로 표시되는지 확인할 수 있습니까? (0) | 2020.07.21 |
---|---|
Matplotlib에 두 번째 (새) 플롯을 만든 다음 나중에 이전 플롯을 만들도록 어떻게 지시합니까? (0) | 2020.07.21 |
2 ~ 3 초 동안 지연을 추가하는 방법 (0) | 2020.07.21 |
프로그래밍 방식으로 선택기 이미지 교체 (0) | 2020.07.21 |
PHP에서 MySQL 정수 필드가 문자열로 반환됩니다 (0) | 2020.07.21 |