[英]To prevent a function from printing in the batch console in Python
Well, the headline seems to me sufficient.好吧,标题在我看来就足够了。 I use some function that at some points print something in the console.我使用一些函数在某些时候在控制台中打印一些东西。 As I can't modify them, I would like to know if there is a solution to not printing while using these functions.由于我无法修改它们,我想知道是否有解决方案可以在使用这些功能时不打印。
Thanks a lot !非常感谢 !
Nico妮可
Yes, you can redirect sys.stdout
:是的,您可以重定向sys.stdout
:
import sys
import os
old_stdout = sys.stdout # backup current stdout
sys.stdout = open(os.devnull, "w")
my_nasty_function()
sys.stdout = old_stdout # reset old stdout
Just replace my_nasty_function
with your actual function.只需将my_nasty_function
替换为您的实际功能即可。
EDIT: Now should work on windows aswell.编辑:现在也应该在 Windows 上工作。
EDIT: Use backup variable to reset stdout is better when someone wraps your function again编辑:当有人再次包装您的函数时,使用备份变量重置标准输出会更好
Constantinius' answer answer is ok, however there is no need to actually open null device. Constantinius 的回答是可以的,但是没有必要实际打开 null 设备。 And BTW, if you want portable null device, there is os.devnull
.顺便说一句,如果你想要便携式空设备,有os.devnull
。
Actually, all you need is a class which will ignore whatever you write to it.实际上,您所需要的只是一个类,它会忽略您写入的任何内容。 So more portable version would be:所以更便携的版本是:
class NullIO(StringIO):
def write(self, txt):
pass
sys.stdout = NullIO()
my_nasty_function()
sys.stdout = sys.__stdout__
. .
Another option would be to wrap your function in a decorator.另一种选择是将您的函数包装在装饰器中。
from contextlib import redirect_stdout
from io import StringIO
class NullIO(StringIO):
def write(self, txt):
pass
def silent(fn):
"""Decorator to silence functions."""
def silent_fn(*args, **kwargs):
with redirect_stdout(NullIO()):
return fn(*args, **kwargs)
return silent_fn
def nasty():
"""Useful function with nasty prints."""
print('a lot of annoying output')
return 42
# Wrap in decorator to prevent printing.
silent_nasty = silent(nasty)
# Same output, but prints only once.
print(nasty(), silent_nasty())
You could use a modified version of this answer to create a "null" output context to wrap the call the function in.您可以使用此答案的修改版本来创建“空”输出上下文来包装函数调用。
That can be done by just passing os.devnull
as the new_stdout
argument to the stdout_redirected()
context manager function when it's used.这可以通过在使用时将os.devnull
作为new_stdout
参数传递给stdout_redirected()
上下文管理器函数来完成。
The currently accepted answer by Constantinius works great in most circumstances, but not in Jupyter notebooks. Constantinius目前接受的答案在大多数情况下都很好用,但在 Jupyter 笔记本中则不然。 Here's how to get it to work (with a reusable function)...这是让它工作的方法(具有可重用的功能)......
TLDR~Instead of using sys.__stout__
, backup sys.stdout
and restore it later on. TLDR~不要使用sys.__stout__
,备份sys.stdout
并在以后恢复它。
In a Jupyter notebook, running sys.stdout == sys.__stdout__
returns false.在 Jupyter 笔记本中,运行sys.stdout == sys.__stdout__
返回 false。 This is because each cell has a separate output stream (instead of the one terminal instance, which is sys.__stdout__
).这是因为每个单元格都有一个单独的输出流(而不是一个终端实例,即sys.__stdout__
)。 So for everyone working with Jupyter notebooks, make sure to back up the old sys.stdout
path and restore it afterwards.因此,对于使用 Jupyter Notebook 的每个人,请确保备份旧的sys.stdout
路径并在之后恢复它。 Here's a function for it:这是它的一个函数:
import sys, os
def deafen(function, *args):
real_stdout = sys.stdout
sys.stdout = open(os.devnull, "w")
output = function(*args)
sys.stdout = real_stdout
return output
Pass to deafen
a function along with its arguments/parameters ( args
).传递给函数及其参数/参数 ( args
) 使其deafen
。 It backs up the old sys.stdout
, switches to os.devnull
and back again itself.它备份旧的sys.stdout
,切换到os.devnull
并返回自身。
For a complete example we can create a second function ( test_function
):对于一个完整的例子,我们可以创建第二个函数( test_function
):
def test_function(first_argument, second_argument, *args):
print(first_argument)
print(second_argument)
print(args)
Now if we try using the test_function
like normal (aka without deafen
) we will get a bunch of output printed onto the screen:现在,如果我们test_function
尝试使用test_function
(也就是没有deafen
),我们将在屏幕上打印出一堆输出:
print("Printing should work fine here")
test_function(32, 12, 1, 32, 1)
However, when using deafen
, we'll get no new output:但是,当使用deafen
,我们不会得到新的输出:
print("That'll be the last thing you see...")
deafen(test_function, 32, 12, 1, 32, 1)
On a side note, the deafen
function still returns a functions output.附带说明一下, deafen
函数仍然返回函数输出。 You can also use deafen
with sys.__stdout__
by replacing sys.stdout = real_stdout
with sys.stdout = sys.__stdout__
(and may as well remove real_stdout = sys.stdout
whilst you're at it).您也可以使用deafen
用sys.__stdout__
通过替换sys.stdout = real_stdout
与sys.stdout = sys.__stdout__
(可能还有去除real_stdout = sys.stdout
,而你在它)。
Hope that helps anyone who is looking for a slightly more robust or flexible solution (likely for Jupyter notebooks, or use with multiple functions)!希望能帮助任何正在寻找更强大或更灵活的解决方案(可能用于 Jupyter 笔记本,或与多种功能一起使用)的人!
Constantinius' solution will work on *nix, but this should work on any platform: Constantinius 的解决方案适用于 *nix,但这应该适用于任何平台:
import sys
import tempfile
sys.stdout = tempfile.TemporaryFile()
# Do crazy stuff here
sys.stdout.close()
#now the temp file is gone
sys.stdout = sys.__stdout__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.