栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在您的python脚本中包括python模块(依赖项)安装

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在您的python脚本中包括python模块(依赖项)安装

在运行实际/主脚本之前,是否可以先包含/调用python模块(依赖项)安装?

  • 一个好方法是使用
    setuptools
    并在中明确列出它们
    install_requires
  • 由于您要提供
    main
    功能,因此您可能还想提供
    entry_points

我已经知道setuptools的基础知识。问题是我可能必须分别调用安装(setup.py)和主脚本(main.py)。

通常这不是问题。首先用

requirements.txt
文件和安装所有内容是很常见的
pip install -rrequirements.txt
。另外,如果您列出依赖项,那么您可以有合理的期望,那就是在调用函数而不依赖于它时,它将存在
try/exceptImporError
。期望所需的依赖项存在并且仅
try/except
用于可选的依赖项是一种合理的方法。

setuptools 101:

创建一个像这样的树结构:

$ tree.├── mymodule│   ├── __init__.py│   └── script.py└── setup.py

您的代码会失败

mymodule
; 让我们想象一些执行简单任务的代码:

# module/script.pydef main():    try:        import requests        print 'requests is present. kudos!'    except importError:        raise RuntimeError('how the heck did you install this?')

这是一个相关的设置:

# setup.pyfrom setuptools import setupsetup(    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/pythonInstalling 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/mymoduleDownloading/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.whlInstalling collected packages: requests, mymodule  Running setup.py install for mymodule    Installing mycommand script to /tmp/test/binSuccessfully installed requests mymoduleCleaning 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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645839.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号