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/