我有这样的文件夹结构:
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
但它不起作用。
当前回答
我认为一种特别的方法是使用环境变量PYTHONPATH,如文档中所述:Python2,Python3
# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH
# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%
其他回答
我已经多次遇到这些问题。我已经多次来到同一页。在我的上一个问题中,我必须从固定目录运行服务器,但每当调试时,我都希望从不同的子目录运行。
import sys
sys.insert(1, /path)
不适合我,因为在不同的模块中,我必须读取不同的*.csv文件,这些文件都在同一目录中。
最后,我想对我有用的不是蟒蛇,而是:
我在要调试的模块上使用了if __main__,它从不同于通常的路径运行。
So:
# On top of the module, instead of on the bottom
import os
if __name__ == '__main__':
os.chdir('/path/for/the/regularly/run/directory')
这里的答案不够清晰,这是在Python 3.6上测试的
使用此文件夹结构:
main.py
|
---- myfolder/myfile.py
其中myfile.py包含内容:
def myfunc():
print('hello')
main.py中的import语句是:
from myfolder.myfile import myfunc
myfunc()
这将打印hello。
我认为一种特别的方法是使用环境变量PYTHONPATH,如文档中所述:Python2,Python3
# Linux & OSX
export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH
# Windows
set PYTHONPATH=C:\path\to\dirWithScripts\;%PYTHONPATH%
以防有人仍在寻找解决方案。这对我有用。
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路径,然后可以通过非相对导入访问类。
据我所知,直接在要导入的函数的文件夹中添加__init__.py文件即可完成此任务。