设置笔记本的默认sys.path [英] Setting a default sys.path for a Notebook

查看:138
本文介绍了设置笔记本的默认sys.path的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所有的.py文件都放在一个文件夹脚本中,而我的所有IPython笔记本都放在一个名为Notebook的文件夹下.

I have all my .py files inside a folder script and all my IPython-notebooks under a folder named Notebook.

脚本中的一个或多个文件中的每个笔记本文件都有多个交叉依赖项.

There are multiple cross dependencies for each notebook file on one or more files on script.

在每个笔记本上都放置sys.path.append似乎很麻烦,我希望有一种方法可以添加默认的查找路径,就像我们在.bash_profile中添加PYTHONPATH一样.

Having sys.path.append on top of every notebook seems cumbersome and I am hoping there is a way to add a default lookup path just like we add PYTHONPATH to .bash_profile.

现在,我执行以下操作:

Now I do the following:

import sys
sys.path.append("<path where DeriveFinalResultSet.py exists>)
import DeriveFinalResultSet as drs

我希望有一个可以进行以下操作的设置:

I wish to have a setting where I can do the below:

import DeriveFinalResultSet as drs

推荐答案

为避免隐藏配置"(即不在源代码控制/特定于机器的内容)并保持您所描述的笔记本/代码分隔,我做类似以下的事情:

To avoid "hidden configurations" (i.e. things that aren't in source control/machine-specific) and to maintain a notebook/code separation like you describe, I do something like the below:

code/
    mymodule.py
    mypackage/
        __init__.py

notebooks/
    mynb.ipynb
    mynb2.ipynb
    paths.py   <--- below

paths.py中:

import sys
import pathlib
sys.path.insert(0, str(pathlib.Path(__file__).parents[1] / 'code'))
# sys.path[0] = str(pathlib.Path(__file__).parents[1] / 'code')

然后在mynb*.ipynb中我可以很高兴地做到:

Then in mynb*.ipynb I can happily do:

import paths
import mymodule, mypackage

后一种形式有效地替换了从空字符串(当前目录)到"code"目录的导入路径,这也许更干净一些.这使得导入对使用os.chdir()之类的东西不敏感.

The latter form effectively replaces the import path from the empty-string (current directory) to the "code" directory, which is perhaps a bit cleaner. This makes imports insensitive to using stuff like os.chdir().

这篇关于设置笔记本的默认sys.path的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆