【发布时间】:2019-11-22 14:06:16
【问题描述】:
这是我的目录树:
prediction_model
├─ prediction_model
| ├─ __init__.py
| ├─ data
| | ├─ SAAA.csv
| | └─ VDFF.csv
| ├─ models.py
| ├─ preprocess.py
| ├─ README.md
| └─ tests
└─ setup.py
这是我的“setup.py”:
from setuptools import find_packages, setup
setup(
name='prediction_model',
version='0.7',
url='https://project.org/',
author='JL',
author_email='jl@project.org',
packages=find_packages(),
scripts=['models.py', 'preprocess.py']
)
这是我的“__init__.py”:
from prediction_model import models
from prediction_model import preprocess
‘models.py’有一个函数main,‘preprocess.py’有一个我想使用的函数run。
我使用以下方式安装项目:
python -m pip install --user .
然后我在 Python 解释器中运行以下代码,但它引发了异常 AttributeError:
>>> import prediction_model
>>> prediction_model.src.main()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'prediction_model' has no attribute 'src'
>>> prediction_model.src.run()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'prediction_model' has no attribute 'src'
>>> import prediction_model
>>> prediction_model.main()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'prediction_model' has no attribute 'main'
>>> prediction_model.run()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'prediction_model' has no attribute 'run'
我做错了什么?
环境:Python 3.7、MacOS。
【问题讨论】:
-
安装后,当您在客户端代码中执行
import prediction_model时,它会隐式运行 __init__.py 文件。因为你在其中做from prediction_model import preprocess, models,所以preprocess和models模块将在你的命名空间中。然后,不要在您的客户端代码中执行prediction_model.src.main(),这会引发AttributeError,因为您的命名空间中没有src对象,您应该只执行prediction_model.preprocess.run()和prediction_model.models.main()。 -
如果你想在你的客户端代码中使用
prediction_model.run()和prediction_model.main(),你应该在你的__init__.py文件中使用from prediction_model.preprocess import run; from prediction_model.models import main。 -
另外,你的
scripts参数应该是['prediction_model/models.py', 'prediction_model/preprocess.py']而不是['models.py', 'preprocess.py'](因为相对路径是根据setup.py 的目录解析的)。此外,models.py 和 preprocess.py 文件的顶部需要一个 shebang 行,否则安装将失败:#!/usr/bin/env python。但是由于它们是 Python 脚本并且是prediction_model包的一部分,因此您应该使用entry_points参数而不是scripts参数,并且您不需要这个 shebang 行。跨度>
标签: python package setuptools setup.py