如何包括Python中不同目录的其他功能的其他文件?
我想将所有文件包括在my_lib
中,因为该目录将包含每个库中使用的大多数功能。在这种情况下,我想导入my_pandas.py
。
我已经添加了包含__ INT __. py
和my_pandas.py
的__ init
的库目录my_lib
。
但是我无法运行以下命令: from my_lib import my_pandas
How can i run from my_lib import my_pandas
command?
I want to include all files in my_lib
as the directory will contains most used function per library. In this case i want to import my_pandas.py
.
I already add the library directory my_lib
which contains __init__.py
and my_pandas.py
.
However i cannot run the following command:from my_lib import my_pandas
How can i run from my_lib import my_pandas
command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,在Python中找到自己的自定义模块。
通过添加
__ Init __. Py
,您将正确制成的my_lib
进入模块中。有两种方法可以使模块正确导入,但是它们归结为同一件事:该模块需要在路径中的目录中以子目录的形式出现。因此,您的解决方案是:
/home/inetvmart/python_apps
,然后在此处运行笔记本而不是内部/home/inetvmart/inetvmart/python_apps/my_lib
(始终包含当前目录在路径中,my_lib
在这种情况下将是当前目录内的子目录)/home/home/inetvmart/inetvmart/python_apps
而不是/home/inetvmart/python_apps/my_lib
到您的路径(然后,父目录将在路径中。因此,您的自定义模块将在此特定情况下是您的目录中的子目录),然后,您可能只能将第二个单元格更改为:
sys.path.append(“/home/inetvmart/python_apps”)
我必须警告您,这是一个有点... hacky ... (修改Python脚本中的路径以确保您的导入成功)。
在中期,您可能想执行以下操作:
/home/<您的用户名>/my_python_modules
$ pythonpath
环境环境中的 文件夹。变量(您可以在.bashrc
/.zshrc
/其他文件中设置),然后您可以在
my_python_modules
中导入自定义模块从机器上的任何地方。Finding your own custom modules in Python is unfortunately a little fiddly.
You have correctly made
my_lib
into a module by adding__init__.py
. There are two ways to get the module to import correctly, but they boil down to the same thing: the module needs to appear as a subdirectory inside a directory that is in your path.Therefore your solutions are:
/home/inetvmart/python_apps
and run your notebook there instead of inside/home/inetvmart/python_apps/my_lib
(the current directory is always included in the path, andmy_lib
will be a subdirectory inside your current directory in this case)/home/inetvmart/python_apps
rather than/home/inetvmart/python_apps/my_lib
to your path (then the parent directory will be in the path. Therefore your custom module will be a subdirectory in a directory that is in your path)In this particular case, then, you can probably just change your second cell to:
sys.path.append("/home/inetvmart/python_apps")
I must warn you that this is a somewhat ... hacky ... approach (modifying the path inside a Python script to ensure your imports succeed).
In the medium term, you may like to do something like:
/home/<your username>/my_python_modules
$PYTHONPATH
environment variable (which you could set in your.bashrc
/.zshrc
/other file)Then you will be able to import the custom modules inside
my_python_modules
from anywhere on your machine.