设置笔记本的默认sys.path

编程入门 行业动态 更新时间:2024-10-27 16:33:29
本文介绍了设置笔记本的默认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

本文发布于:2023-11-23 21:19:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:笔记本   sys   path

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!