有没有办法在运行实际/主脚本之前首先包含/调用 python 模块(依赖项)安装?
例如,在我的 main.py 中:
import os, sys
import MultipartPostHandler
def main():
# do stuff here
但是 MultipartPostHandler 还没有安装,所以我想先安装它 实际上正在运行 main.py...但是以自动方式运行。当我说自动时,我的意思是我将只调用一次脚本来启动依赖项安装,然后是主脚本的实际功能。 (不知何故,有点类似于maven。但我只需要安装部分)
我已经了解了 setuptools 的基础知识。问题是我可能必须分别调用安装 (setup.py) 和主脚本 (main.py)。
非常感谢任何想法。提前致谢!
最佳答案
Is there a way to include/invoke python module(s) (dependencies) installation first, before running the actual/main script?
- 一个好方法是使用
setuptools
并在install_requires
中明确列出它们. - 由于您提供了一个
main
函数,您可能还想提供entry_points
。 .
I already know the basics of setuptools. The problem is I may have to call the installation (setup.py) and the main script (main.py) separately.
这通常不是问题。首先使用 requirements.txt
文件和 pip install -r requirements.txt
安装所有内容是很常见的。另外,如果您列出依赖项,那么您可以合理地期望它会在您的函数被调用时存在,而不依赖于 try/except ImporError
。期望存在必需的依赖项并且仅对可选依赖项使用 try/except
是一种合理的方法。
设置工具 101:
像这样创建一个树结构:
$ 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 的更多有用命令:
如果你想使用 argparse
那么......
# module/script.py
import argparse
def foobar(args):
# ...
def main():
parser = argparse.ArgumentParser()
# parser.add_argument(...)
args = parser.parse_args()
foobar(args)
关于python - 在 python 脚本中包含 python 模块(依赖项)安装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26081948/