简体   繁体   English

IPython %run 忽略打印命令

[英]IPython %run ignore print commands

I'm using several Jupyter Notebooks to split the tasks between different modules.我正在使用几个 Jupyter Notebooks 在不同模块之间拆分任务。 In my main notebook I call another module %run another_module.ipynb which loads all my data.在我的主笔记本中,我调用另一个模块%run another_module.ipynb来加载我的所有数据。 However, it also plots and prints everything I have in another_module.ipynb .但是,它还会绘制和打印我在another_module.ipynb 中的所有内容。

I want to keep the plots in another_module.ipynb to help me visualise the data but I don't want to reprint everything when calling run another_module.ipynb .我想将绘图保留在another_module.ipynb 中以帮助我可视化数据,但我不想在调用run another_module.ipynb时重新打印所有内容。 Is there an option to prevent priniting this?有没有一个选项可以防止打印这个?

Thanks谢谢

You could:你可以:

  1. Override the print function and make it a no-op:覆盖print功能并使其成为空操作:
_print_function = print  # create a backup in case you need it later
globals()["print"] = lambda *args, **kwargs: None
  1. Run the file with the -i flag.使用-i标志运行文件。 Without -i , the file is run in a new namespace, so your modifications to the global variables are lost;如果没有-i ,文件将在新的命名空间中运行,因此您对全局变量的修改将丢失; with -i , the file is run in the current namespace.使用-i ,文件在当前命名空间中运行。
%run -i another_module.ipynb

If you're using other methods to print logs (eg, sys.stdout.write() , logging ), it would be harder to create mocks for them.如果您使用其他方法打印日志(例如, sys.stdout.write()logging ),则为它们创建模拟将更加困难。 In that case, I would suggest redirecting the stdout or stderr pipe to /dev/null :在这种情况下,我建议将stdoutstderr管道重定向到/dev/null

import os
import sys
sys.stdout = fopen(os.devnull, "w")
%run -i another_module.ipynb

Both methods are considered hacks and should only be used when you know the consequences.这两种方法都被认为是黑客行为,只有在您知道后果时才应该使用。 The better thing to do here is to change your code in the notebook, either to add a --verbose flag to control logging, or use some logging library (eg, logging ) that supports turning off logging entirely.在这里做的更好的事情是更改笔记本中的代码,或者添加一个--verbose标志来控制日志记录,或者使用一些支持完全关闭日志记录的日志库(例如, logging )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM