ipython Notebook中的python访问功能 [英] python access functions in ipython notebook
问题描述
我有一个存储在.py文件中的函数,称为my_methods.
I have a function stored in a .py file, call it my_methods.
def print_text(myText):
print myText
我正在使用ipython笔记本进行开发(本地服务器),并且my_methods文件经常更改.
I'm using ipython notebook to do my development (local server), and the my_methods file is frequently changing.
我想使用runipy通过引用my_methods中函数的shell脚本来运行其他ipython笔记本.例如,从外壳程序脚本启动的一个ipython笔记本看起来像这样:
I'd like to use runipy to run other ipython notebooks via a shell script that reference the functions within my_methods. For example, one ipython notebook being launched from a shell script would look like this:
import my_methods as mm
mm.print_text("print me")
如何进行设置,以便import my_methods行可以从ipython笔记本(.ipynb)而不是.py版本获取print_text函数?当前,我必须将my_methods笔记本下载为.py文件,这会导致版本控制问题(my_methods的.ipynb版本与下载的.py版本不同)
How do I set this up so that the import my_methods line can get the print_text function from the ipython notebook (.ipynb), instead of the .py version? Currently, I'd have to download the my_methods notebook as a .py file, which is causing version control issues (the .ipynb version of my_methods is different than the downloaded .py version)
感谢您的帮助!
编辑
因此,在阅读了显示为答案的博客文章之后,我对find_notebook函数进行了一些修改.如果没有提供ipython笔记本的路径,我只是通过sys.path而不是当前目录读取它.我也没有像以前那样在Linux机器上运行,因此它使我更轻松地将所有添加的python文件维护在一个单独的目录中,该目录包含在path变量中.我将以下代码保存在名为iPyLoader的模块中,然后首先将其导入其他模块:
So after reading through the blog post that was shown as the answer I made a slight modification to the find_notebook function. If a path for the ipython notebook isn't supplied,I just had it read through sys.path, rather than the current directory. I'm also not running on a linux machine like they were, so it made it easier for me to maintain all of my added python files in a separate directory, which is included in my path variable. I saved the following code in a module called iPyLoader, and then import it first in my other modules:
import io, os, sys, types
from IPython import get_ipython
from IPython.nbformat import current
from IPython.core.interactiveshell import InteractiveShell
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 = sys.path #EDITED HERE RATHER THAN CURRENT DIRECTORY
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 IPython 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)
print ("importing IPython notebook from %s" % path)
# load the notebook object
with io.open(path, 'r', encoding='utf-8') as f:
nb = current.read(f, 'json')
# 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.worksheets[0].cells:
if cell.cell_type == 'code' and cell.language == 'python':
# transform the input to executable Python
code = self.shell.input_transformer_manager.transform_cell(cell.input)
# run the code in themodule
exec(code, mod.__dict__)
finally:
self.shell.user_ns = save_user_ns
return mod
class NotebookFinder(object):
"""Module finder that locates IPython 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]
sys.meta_path.append(NotebookFinder())
然后我的示例文件可能会运行类似的
then my sample file might run something like this
import iPyLoader
import testnotebook as printer #this is an .ipynb file
printer.myprinter("test")
,输出将是:
importing IPython notebook from C:\Python27\lib\testnotebook.ipynb
test
推荐答案
A good approximation is exposed here.
因为ipython笔记本不是常规的纯文本,所以不存在简便的方法.
Easy way not exist because ipython notebook is not regular plain text.
这篇关于ipython Notebook中的python访问功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!