我有这样的文件夹结构:

application
├── app
│   └── folder
│       └── file.py
└── app2
    └── some_folder
        └── some_file.py

如何从file.py或some_file.py中导入函数?我尝试了:

from application.app.folder.file import func_name

但它不起作用。


当前回答

在我的情况下,我有一个类要导入。我的文件如下:

# /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

其他回答

将application作为python项目的根目录,在application、app和文件夹文件夹中创建一个空__init__.py文件。然后在some_file.py中进行如下更改以获得func_name的定义:

import sys
sys.path.insert(0, r'/from/root/directory/application')

from application.app.folder.file import func_name ## You can also use '*' wildcard to import all the functions in file.py file.
func_name()

我的解决方案。他们在包中拥有所有必需的init__.py,但import仍然不起作用。

import sys
import os
sys.path.insert(0, os.getcwd())

import application.app.folder.file as file

如果您只想运行脚本而不是实际导入脚本,则exec命令将执行此操作

exec(open('/full/or/relative/path').read())

以防有人仍在寻找解决方案。这对我有用。

Python将包含您启动的脚本的文件夹添加到PYTHONPATH中,因此如果您运行

python application/app2/some_folder/some_file.py

只有文件夹application/app2/some_folder被添加到路径(而不是执行命令的基本目录)。相反,将文件作为模块运行,并在some_folder目录中添加__init__.py。

python -m application.app2.some_folder.some_file

这将把基本目录添加到python路径,然后可以通过非相对导入访问类。

在linux上的python3中为我工作

import sys  
sys.path.append(pathToFolderContainingScripts)  
from scriptName import functionName #scriptName without .py extension