您可以将父目录添加到PYTHONPATH
,为了实现这一点,您可以在sys.path
中列出的"模块搜索路径"中使用依赖于操作系统的路径.因此,您可以轻松添加父目录,如下所示:
import sys
sys.path.insert(0, '..')
from instance import config
请注意,前面的代码使用相对路径,因此必须在同一位置启动文件,否则可能无法运行.要从任何地方emits ,可以使用pathlib
模块.
from pathlib import Path
import sys
path = str(Path(Path(__file__).parent.absolute()).parent.absolute())
sys.path.insert(0, path)
from instance import config
然而,前面的方法更像是一种黑客行为,为了把事情做好,你首先需要根据这篇非常详细的博文python packaging来reshape 你的项目 struct ,使用src
文件夹的推荐方法.
project
├── CHANGELOG.rst
├── README.rst
├── requirements.txt
├── setup.py
├── src
│ ├── api
│ │ ├── api.py
│ │ └── __init__.py
│ ├── instance
│ │ ├── config.py
│ │ └── __init__.py
│ └── package
│ ├── app.py
│ └── __init__.py
└── tests
└── __init__.py
请注意,您实际上并不需要requirements.txt
,因为您可以在setup.py
中声明依赖项.
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
with io.open(
join(dirname(__file__), *names),
encoding=kwargs.get('encoding', 'utf8')
) as fh:
return fh.read()
setup(
name='nameless',
version='1.644.11',
license='BSD-2-Clause',
description='An example package. Generated with cookiecutter-pylibrary.',
author='mpr',
author_email='contact@ionelmc.ro',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
zip_safe=False,
classifiers=[
# complete classifier list: http://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: Unix',
'Operating System :: POSIX',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
# uncomment if you test on these interpreters:
# 'Programming Language :: Python :: Implementation :: IronPython',
# 'Programming Language :: Python :: Implementation :: Jython',
# 'Programming Language :: Python :: Implementation :: Stackless',
'Topic :: Utilities',
],
keywords=[
# eg: 'keyword1', 'keyword2', 'keyword3',
],
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*',
install_requires=[
# eg: 'aspectlib==1.1.1', 'six>=1.7',
],
extras_require={
# eg:
# 'rst': ['docutils>=0.11'],
# ':python_version=="2.6"': ['argparse'],
},
setup_requires=[
# 'pytest-runner',
],
entry_points={
'console_scripts': [
'api = api.api:main',
]
},
)
my api.py
的内容:
from instance import config
def main():
print("imported")
config.config()
my config.py
的内容:
def config():
print("config imported successfully")
你可以找到之前的here条
- 可选但推荐:创建一个虚拟环境,我使用
venv
(Python 3.3<;=)在项目的根目录中:
python -m venv .
并激活:
source bin/activate
使用pip install -e .
(带点)命令inside the root of the project
- 您的import
from instance import config
现在可以运行了,以确认您可以运行api.带:
python src/api/api.py