在运行实际/主脚本之前,是否可以先包含/调用python模块(依赖项)安装?
我已经知道setuptools的基础知识。问题是我可能必须分别调用安装(setup.py)和主脚本(main.py)。
通常这不是问题。首先用requirements.txt
文件和安装所有内容是很常见的pip install -r requirements.txt
。另外,如果您列出依赖项,那么您可以有合理的期望,那就是在调用函数而不依赖于它时,它将存在try/except ImporError
。期望所需的依赖项存在并且仅try/except
用于可选的依赖项是一种合理的方法。
创建一个像这样的树结构:
$ tree
.
├── mymodule
│ ├── __init__.py
│ └── script.py
└── setup.py
您的代码会失败mymodule
; 让我们想象一些执行简单任务的代码:
# module/script.py
def main():
try:
import requests
print 'requests is present. kudos!'
except ImportError:
raise RuntimeError('how the heck did you install this?')
这是一个相关的设置:
# setup.py
from setuptools import setup
setup(
name='mymodule',
packages=['mymodule'],
entry_points={
'console_scripts' : [
'mycommand = mymodule.script:main',
]
},
install_requires=[
'requests',
]
)
这将使您main
可以作为命令使用,并且还将照顾安装所需的依赖项(例如requests
)
~tmp damien$ virtualenv test && source test/bin/activate && pip install mymodule/
New python executable in test/bin/python
Installing setuptools, pip...done.
Unpacking ./mymodule
Running setup.py (path:/var/folders/cs/nw44s66532x_rdln_cjbkmpm000lk_/T/pip-9uKQFC-build/setup.py) egg_info for package from file:///tmp/mymodule
Downloading/unpacking requests (from mymodule==0.0.0)
Using download cache from /Users/damien/.pip_download_cache/https%3A%2F%2Fpypi.python.org%2Fpackages%2F2.7%2Fr%2Frequests%2Frequests-2.4.1-py2.py3-none-any.whl
Installing collected packages: requests, mymodule
Running setup.py install for mymodule
Installing mycommand script to /tmp/test/bin
Successfully installed requests mymodule
Cleaning up...
(test)~tmp damien$ mycommand
requests is present. kudos!
如果您想使用argparse
…
# module/script.py
import argparse
def foobar(args):
# ...
def main():
parser = argparse.ArgumentParser()
# parser.add_argument(...)
args = parser.parse_args()
foobar(args)