gpt4 book ai didi

用于检查模块是否存在的 python 脚本,否则安装模块

转载 作者:行者123 更新时间:2023-12-04 02:09:59 26 4
gpt4 key购买 nike

我有这个简单的 Python 脚本。我想在运行 Python 模块之前包含某种条件来检查它(在我下面的示例 subprocess 中)。如果该模块不存在,请安装该模块,然后运行脚本。如果模块存在,则跳过模块的安装并运行脚本。我正在努力应对我在网上看到的大多数类似情况。

import subprocess
ls_output = subprocess.check_output(['ls'])
print ls_output

最佳答案

以下是检查是否安装了 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)

关于用于检查模块是否存在的 python 脚本,否则安装模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39584442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com