python - "import or install"的简写?

标签 python

Python 中有这方面的简写吗?

#!/usr/bin/python3
try:
  import tornado
except ImportError:
  print("Import not found, installing ...")
  import os
  os.system("sudo pip3 install tornado");
  import tornado

这个想法是让代码“正常工作,不问任何问题”,而不是提示 ImportError。另外,上面的代码需要我写“tornado”3次,这不是很DRY。也就是说,是否有一些有效相当于:

import_and_dont_complain "tornado"

最佳答案

正确的解决方案是在 setup.py 中声明依赖项。

from setuptools import setup

setup(name='herro',
      version='0.1',
      description='Is anybody there?',
      url='http://herro.example.com/',
      author='yourself',
      author_email='<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3daccd6e3c6dbc2ced3cfc68dc0ccce" rel="noreferrer noopener nofollow">[email protected]</a>',
      license='GPL',
      packages=['herro'],
      install_requires=['tornado'],  # <----- here
      zip_safe=False)

http://python-packaging.readthedocs.org/en/latest/dependencies.html

关于python - "import or install"的简写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33810617/

相关文章:

python - 无法绘制数据

python - 用自定义图案填充 pygame 字体

python - 给定一个文本文件的 URL,读取文本文件内容的最简单方法是什么?

python - 如何在 macos 上为 python27 安装 jsonrpc

python - Python 中一个元组或列表可以包含多少个?

python - 在 Windows 上用 Python 演示多核加速的一些示例代码是什么?

python - 如何使用 Python 重命名 Google Drive 文件

Python:回调问题

python - 使用 Django 处理上传的文件

python - 在 Python 中按地址拆分字符串,就像在 C 中一样(Python 的字符串切片)