0%

jupyter lab实现跨文件的函数调用

在python各类编译器中,jupyter notebook真的是非常非常棒的调试工具,但是jupyter notebook在大工程方面却是逊于pycharm的,其虽然调试很方便,但是却不是像pycharm一样打开一整个文件夹,所以其团队又开发了jupyter lab来弥补缺陷,而jupyter lab的代码补齐真的又一言难尽,由于jupyter lab本身并不是完善,用了kite工具辅助代码补齐,即使操作完全没问题,kite也可能不工作,工作了也发现kite速度真的超慢又浪费CPU

算了,毕竟jupyter lab已经是一大进步了,平时我们写代码,模块化是非常重要的,所以经常会分文件进行写函数,然后跨文件调用,python中跨文件调用很简单,如果想在文件A中调用文件B中的max函数,如下即可:

1
2
3
4
5
import sys
# 待引用的py文件B路径加到了搜索列表里
sys.path.append(r"D:\python\test")
import B
B.max()

或者如下

1
2
3
4
5
import sys
# 待引用的py文件路径加到了搜索列表里
sys.path.append(r"D:\python\test")
form B import max
max()

A和B若是在同一路径下,可以无需添加路径。

但上述的方法是用来py文件跨文件调用的,而jupyter中的文件不是py而是ipynb文件,那么上述这个方法就没法在jupyter中用了,官方给出了一个解决方法,先在jupyter中建立一个文件,写入如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# coding: utf-8

# In[ ]:


import io, os,sys,types
from IPython import get_ipython
from nbformat import read
from IPython.core.interactiveshell import InteractiveShell

class NotebookFinder(object):
"""Module finder that locates Jupyter Notebooks"""
def __init__(self):
self.loaders = {}

def find_module(self, fullname, path=None):
nb_path = find_notebook(fullname, path)
if not nb_path:
return

key = path
if path:
# lists aren't hashable
key = os.path.sep.join(path)

if key not in self.loaders:
self.loaders[key] = NotebookLoader(path)
return self.loaders[key]

def find_notebook(fullname, path=None):
"""find a notebook, given its fully qualified name and an optional path

This turns "foo.bar" into "foo/bar.ipynb"
and tries turning "Foo_Bar" into "Foo Bar" if Foo_Bar
does not exist.
"""
name = fullname.rsplit('.', 1)[-1]
if not path:
path = ['']
for d in path:
nb_path = os.path.join(d, name + ".ipynb")
if os.path.isfile(nb_path):
return nb_path
# let import Notebook_Name find "Notebook Name.ipynb"
nb_path = nb_path.replace("_", " ")
if os.path.isfile(nb_path):
return nb_path

class NotebookLoader(object):
"""Module Loader for Jupyter Notebooks"""
def __init__(self, path=None):
self.shell = InteractiveShell.instance()
self.path = path

def load_module(self, fullname):
"""import a notebook as a module"""
path = find_notebook(fullname, self.path)

print ("importing Jupyter notebook from %s" % path)

# load the notebook object
with io.open(path, 'r', encoding='utf-8') as f:
nb = read(f, 4)


# create the module and add it to sys.modules
# if name in sys.modules:
# return sys.modules[name]
mod = types.ModuleType(fullname)
mod.__file__ = path
mod.__loader__ = self
mod.__dict__['get_ipython'] = get_ipython
sys.modules[fullname] = mod

# extra work to ensure that magics that would affect the user_ns
# actually affect the notebook module's ns
save_user_ns = self.shell.user_ns
self.shell.user_ns = mod.__dict__

try:
for cell in nb.cells:
if cell.cell_type == 'code':
# transform the input to executable Python
code = self.shell.input_transformer_manager.transform_cell(cell.source)
# run the code in themodule
exec(code, mod.__dict__)
finally:
self.shell.user_ns = save_user_ns
return mod
sys.meta_path.append(NotebookFinder())

上述代码中try后的for在写入文件中的时候,编译器可能会提醒for的缩进有问题,会进行标红,不用管,缩进是没问题的。

然后我们给这个文件另存为后缀为py的文件,在jupyter notebook中进行如下另存为。

千万不要直接rename,直接rename是有问题的,所以不要直接rename。另存为py文件后,把这个文件放到和文件A同一个路径下,那么我们就可以如下在文件A中调用B中的函数了:

1
2
3
4
5
import 文件名 #刚刚另存为py的那个文件名
import sys
sys.path.append(r"D:\python\test") # 待引用的py文件B路径加到了搜索列表里
import B
B.max()

如果这时候提醒你另存为的那个文件找不到,那么就需要看看你的另存为py的那个文件名名字是否是大写字母开头,如果是小写开头也可能出问题(真的就巨坑)。

然后在运行就不会提醒说找不到那个py文件了。但是有可能有如下这样报错

说B文件中没有这个函数,这个一般是新建文件的时候在不同虚拟环境下创建的问题,如果是jupyter lab,如下修改即可

如果是notebook,在命令行中修改。

最后运行完全没问题,如果我们继续在B中写其他函数,或者修改原来的max函数,在A中运行却得不到想要的结果,这个就是A中对B进行了缓存导致的,所以需要shut down这个kernel(即文件A),然后再打开运行即可。

深深体会到jupyter为什么在大工程方面被pycharm锤了,文件调用以及打开文件夹等功能真的需要改进,但不得不说jupyter 调试超棒

- - - - - - - - - - - - - - 本文结束啦,感谢您的观看 - - - - - - - - - - - - - -