python - 导入 .ipynb 笔记本而不运行它?
问题描述
我有 2 个.ipynb笔记本,A 和 B。我想在 B 中使用 A 的一些功能/类。不运行 A。
笔记本“A”:
class class_i_want_to_import_to_use:
def __init__(self, x):
print (x)
print ("Main that i don't want to run when importing ")
笔记本乙
import import_ipynb
import A
b=A.class_i_want_to_import_to_use("run it in B notebook")
出去:
importing Jupyter notebook from A.ipynb
Main that i don't want to run when importing #DONT WANT TO SEE THIS
run it in B notebook
这是可能的还是我需要将我的所有功能分离到一个不运行任何东西的笔记本中?
解决方案
你需要使用这个__name__ == 'main'
技巧。
在这里查看更多信息if __name__ == "__main__": 怎么办?
class class_i_want_to_import_to_use:
def __init__(self, x):
print (x)
#this block will not be executed by import
#but it will get executed when running the script
if __name__ == 'main':
print ("Main that i don't want to run when importing ")
推荐阅读
- android - 如何在 Android Studio 中隐藏警报对话框?
- sql-server - SQL Server 代理 Powershell 作业返回空白
- go - 使用 Gorm 模型对可为空的 TIMESTAMP 进行建模的首选方法?
- powershell - 在 PowerShell 中使用 Copy-Item 的问题
- vsphere - 我们可以验证 ovf 文件中设置的 guestInfo 属性的值吗
- eclipse - 在开始 Eclipse 调试之前运行本地命令
- visual-studio - 将 .dll 文件添加到 Visual Studio,并在代码中打开
- bash - 如果其他条件,则无法在 bash 速记中增加变量
- java - Junit 5 找不到测试(Spring Boot)
- android - Change search button color in keyboard