我有这样的文件夹结构:
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
如何从file.py或some_file.py中导入函数?我尝试了:
from application.app.folder.file import func_name
但它不起作用。
我有这样的文件夹结构:
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
如何从file.py或some_file.py中导入函数?我尝试了:
from application.app.folder.file import func_name
但它不起作用。
当前回答
如果从特定路径加载模块的目的是帮助您开发自定义模块,则可以在测试脚本的同一文件夹中创建指向自定义模块根目录的符号链接。对于在该文件夹中运行的任何脚本,此模块引用将优先于以相同名称安装的任何其他模块。
我在Linux上测试了这个,但它应该可以在任何支持符号链接的现代操作系统中运行。
这种方法的一个优点是,您可以指向位于您自己的本地SVC分支工作副本中的模块,这可以大大简化开发周期,并减少管理不同版本模块的故障模式。
其他回答
我多次遇到同一个问题,所以我想分享我的解决方案。
Python版本:3.X
以下解决方案适用于在Python 3.X版本中开发应用程序的人,因为自2020年1月1日以来,Python 2不受支持。
项目结构
在python3中,由于隐式命名空间包,项目子目录中不需要__init__.py。请参见Python 3.3中的包是否不需要init.py+
Project
├── main.py
├── .gitignore
|
├── a
| └── file_a.py
|
└── b
└── file_b.py
问题陈述
在file_b.py中,我想在文件夹a下的file_a.py中导入一个类a。
解决
#1快速但肮脏的方式
不安装软件包,就像您当前正在开发一个新项目
使用try-catch检查是否存在错误。代码示例:
import sys
try:
# The insertion index should be 1 because index 0 is this file
sys.path.insert(1, '/absolute/path/to/folder/a') # the type of path is string
# because the system path already have the absolute path to folder a
# so it can recognize file_a.py while searching
from file_a import A
except (ModuleNotFoundError, ImportError) as e:
print("{} fileure".format(type(e)))
else:
print("Import succeeded")
#2安装软件包
安装应用程序后(在本文中,不包括安装教程)
你可以简单地
try:
from __future__ import absolute_import
# now it can reach class A of file_a.py in folder a
# by relative import
from ..a.file_a import A
except (ModuleNotFoundError, ImportError) as e:
print("{} fileure".format(type(e)))
else:
print("Import succeeded")
编码愉快!
你可以使用pip的pipinstall-e。命令您必须在项目目录的根目录中创建一个名为setup.py的文件,该文件包含以下内容:
from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='my_project',
author='author',
license='MIT',
)
然后,输入pipinstall-e。而在项目的根目录中。这将使所有目录都能以其名称作为模块进行调用。例如,如果根目录包含子目录module1和module2,每个子目录中都有脚本,则可以使用以下命令从任何子目录访问module1:
将模块1.script1导入为script1
我通常会创建一个指向要导入的模块的符号链接。符号链接确保Python解释器可以在当前目录(将其他模块导入的脚本)中找到模块;稍后工作结束后,可以删除符号链接。此外,您应该忽略.gitignore中的符号链接,这样就不会意外地将符号链接模块提交到repo中。这种方法甚至可以让您成功地处理与正在执行的脚本并行的模块。
ln -s ~/path/to/original/module/my_module ~/symlink/inside/the/destination/directory/my_module
我的解决方案。他们在包中拥有所有必需的init__.py,但import仍然不起作用。
import sys
import os
sys.path.insert(0, os.getcwd())
import application.app.folder.file as file
据我所知,直接在要导入的函数的文件夹中添加__init__.py文件即可完成此任务。