我有这个简单的Python脚本。我希望在运行之前包含一些检查Python模块的条件(在我的示例中subprocess
)。如果模块不存在,请安装模块然后运行脚本。如果模块存在,请跳过模块的安装并运行脚本。我正在努力解决我在网上看到的大多数类似情况。
import subprocess
ls_output = subprocess.check_output(['ls'])
print ls_output
答案 0 :(得分:2)
以下是检查pycurl是否已安装的方法:
# if you want to now install pycurl and run it, it is much trickier
# technically, you might want to check if pip is installed as well
import sys
import pip
def install(package):
pip.main(['install', package])
try:
import pycurl
except ImportError:
print 'pycurl is not installed, installing it now!'
install('pycurl')
# not recommended because http://stackoverflow.com/questions/7271082/how-to-reload-a-modules-function-in-python
import pycurl
. . . .
# better option:
print 'just installed pycurl, please rerun this script at your convenience'
sys.exit(1)