我有这样的文件夹结构:
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
但它不起作用。
当前回答
我正在处理项目a,我希望用户通过pip-install a使用以下文件列表进行安装:
.
├── setup.py
├── MANIFEST.in
└── a
├── __init__.py
├── a.py
└── b
├── __init__.py
└── b.py
设置.py
from setuptools import setup
setup (
name='a',
version='0.0.1',
packages=['a'],
package_data={
'a': ['b/*'],
},
)
歧管in
recursive-include b *.*
a/init.py
from __future__ import absolute_import
from a.a import cats
import a.b
a/a.py
cats = 0
a/b/init.py
from __future__ import absolute_import
from a.b.b import dogs
a/b/b.py
dogs = 1
我通过在MANIFEST.in目录下运行以下命令来安装模块:
python setup.py install
然后,在我的文件系统上的一个完全不同的位置上,我可以运行:
import a
dir(a)
这证实了a.ats确实等于0,a.b.dogs确实等于1,正如预期的那样。
其他回答
我认为一种特别的方法是使用环境变量PYTHONPATH,如文档中所述:Python2,Python3
# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH
# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%
以防有人仍然需要解决方案,但在上面的答案中没有找到解决方案。这对我有用:
我有这样的文件夹结构:
a
└── b
├── c1
| └── d
| └── a_script.py
└── c2
└── a_lib.py
我需要将a_lib.py包含在a_script.py中。这就是我如何解决c2无法识别的错误:
import sys
from pathlib import Path
path_scripts = Path(__file__).resolve().parents[2]
sys.path.append(str(path_scripts))
from c2 import a_lib
我多次遇到同一个问题,所以我想分享我的解决方案。
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")
编码愉快!
在Python 3.4及更高版本中,您可以直接从源文件导入(链接到文档)。这不是最简单的解决方案,但为了完整起见,我将此答案包括在内。
这里有一个例子。首先,要导入的文件名为foo.py:
def announce():
print("Imported!")
导入上述文件的代码深受文档中示例的启发:
import importlib.util
def module_from_file(module_name, file_path):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
foo = module_from_file("foo", "/path/to/foo.py")
if __name__ == "__main__":
print(foo)
print(dir(foo))
foo.announce()
输出:
<module 'foo' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
请注意,变量名、模块名和文件名不必匹配。此代码仍然有效:
import importlib.util
def module_from_file(module_name, file_path):
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
baz = module_from_file("bar", "/path/to/foo.py")
if __name__ == "__main__":
print(baz)
print(dir(baz))
baz.announce()
输出:
<module 'bar' from '/path/to/foo.py'>
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'announce']
Imported!
Python 3.1中引入了以编程方式导入模块,使您能够更好地控制模块的导入方式。有关更多信息,请参阅文档。
在我的情况下,我有一个类要导入。我的文件如下:
# /opt/path/to/code/log_helper.py
class LogHelper:
# stuff here
在我的主文件中,我通过以下方式包含了代码:
import sys
sys.path.append("/opt/path/to/code/")
from log_helper import LogHelper