首页 > 解决方案 > 导入 .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

这是可能的还是我需要将我的所有功能分离到一个不运行任何东西的笔记本中?

标签: pythonjupyter-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 ")

推荐阅读