下载安装setuptools

article/2025/10/10 13:50:32

复制下面这段代码存为python格式,运行,可自动下载

 

#!/usr/bin/env python"""
Setuptools bootstrapping installer.Maintained at https://github.com/pypa/setuptools/tree/bootstrap.Run this script to install or upgrade setuptools.This method is DEPRECATED. Check https://github.com/pypa/setuptools/issues/581 for more details.
"""import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlibfrom distutils import logtry:from urllib.request import urlopen
except ImportError:from urllib2 import urlopentry:from site import USER_SITE
except ImportError:USER_SITE = None# 33.1.1 is the last version that supports setuptools self upgrade/installation.
DEFAULT_VERSION = "33.1.1"
DEFAULT_URL = "https://pypi.io/packages/source/s/setuptools/"
DEFAULT_SAVE_DIR = os.curdir
DEFAULT_DEPRECATION_MESSAGE = "ez_setup.py is deprecated and when using it setuptools will be pinned to {0} since it's the last version that supports setuptools self upgrade/installation, check https://github.com/pypa/setuptools/issues/581 for more info; use pip to install setuptools"MEANINGFUL_INVALID_ZIP_ERR_MSG = 'Maybe {0} is corrupted, delete it and try again.'log.warn(DEFAULT_DEPRECATION_MESSAGE.format(DEFAULT_VERSION))def _python_cmd(*args):"""Execute a command.Return True if the command succeeded."""args = (sys.executable,) + argsreturn subprocess.call(args) == 0def _install(archive_filename, install_args=()):"""Install Setuptools."""with archive_context(archive_filename):# installinglog.warn('Installing Setuptools')if not _python_cmd('setup.py', 'install', *install_args):log.warn('Something went wrong during the installation.')log.warn('See the error message above.')# exitcode will be 2return 2def _build_egg(egg, archive_filename, to_dir):"""Build Setuptools egg."""with archive_context(archive_filename):# building an egglog.warn('Building a Setuptools egg in %s', to_dir)_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)# returning the resultlog.warn(egg)if not os.path.exists(egg):raise IOError('Could not build the egg.')class ContextualZipFile(zipfile.ZipFile):"""Supplement ZipFile class to support context manager for Python 2.6."""def __enter__(self):return selfdef __exit__(self, type, value, traceback):self.close()def __new__(cls, *args, **kwargs):"""Construct a ZipFile or ContextualZipFile as appropriate."""if hasattr(zipfile.ZipFile, '__exit__'):return zipfile.ZipFile(*args, **kwargs)return super(ContextualZipFile, cls).__new__(cls)@contextlib.contextmanager
def archive_context(filename):"""Unzip filename to a temporary directory, set to the cwd.The unzipped target is cleaned up after."""tmpdir = tempfile.mkdtemp()log.warn('Extracting in %s', tmpdir)old_wd = os.getcwd()try:os.chdir(tmpdir)try:with ContextualZipFile(filename) as archive:archive.extractall()except zipfile.BadZipfile as err:if not err.args:err.args = ('', )err.args = err.args + (MEANINGFUL_INVALID_ZIP_ERR_MSG.format(filename),)raise# going in the directorysubdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])os.chdir(subdir)log.warn('Now working in %s', subdir)yieldfinally:os.chdir(old_wd)shutil.rmtree(tmpdir)def _do_download(version, download_base, to_dir, download_delay):"""Download Setuptools."""py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys)tp = 'setuptools-{version}-{py_desig}.egg'egg = os.path.join(to_dir, tp.format(**locals()))if not os.path.exists(egg):archive = download_setuptools(version, download_base,to_dir, download_delay)_build_egg(egg, archive, to_dir)sys.path.insert(0, egg)# Remove previously-imported pkg_resources if present (see# https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).if 'pkg_resources' in sys.modules:_unload_pkg_resources()import setuptoolssetuptools.bootstrap_install_from = eggdef use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,to_dir=DEFAULT_SAVE_DIR, download_delay=15):"""Ensure that a setuptools version is installed.Return None. Raise SystemExit if the requested versionor later cannot be installed."""to_dir = os.path.abspath(to_dir)# prior to importing, capture the module state for# representative modules.rep_modules = 'pkg_resources', 'setuptools'imported = set(sys.modules).intersection(rep_modules)try:import pkg_resourcespkg_resources.require("setuptools>=" + version)# a suitable version is already installedreturnexcept ImportError:# pkg_resources not available; setuptools is not installed; downloadpassexcept pkg_resources.DistributionNotFound:# no version of setuptools was found; allow downloadpassexcept pkg_resources.VersionConflict as VC_err:if imported:_conflict_bail(VC_err, version)# otherwise, unload pkg_resources to allow the downloaded version to#  take precedence.del pkg_resources_unload_pkg_resources()return _do_download(version, download_base, to_dir, download_delay)def _conflict_bail(VC_err, version):"""Setuptools was imported prior to invocation, so it isunsafe to unload it. Bail out."""conflict_tmpl = textwrap.dedent("""The required version of setuptools (>={version}) is not available,and can't be installed while this script is running. Pleaseinstall a more recent version first, using'easy_install -U setuptools'.(Currently using {VC_err.args[0]!r})""")msg = conflict_tmpl.format(**locals())sys.stderr.write(msg)sys.exit(2)def _unload_pkg_resources():sys.meta_path = [importerfor importer in sys.meta_pathif importer.__class__.__module__ != 'pkg_resources.extern']del_modules = [name for name in sys.modulesif name.startswith('pkg_resources')]for mod_name in del_modules:del sys.modules[mod_name]def _clean_check(cmd, target):"""Run the command to download target.If the command fails, clean up before re-raising the error."""try:subprocess.check_call(cmd)except subprocess.CalledProcessError:if os.access(target, os.F_OK):os.unlink(target)raisedef download_file_powershell(url, target):"""Download the file at url to target using Powershell.Powershell will validate trust.Raise an exception if the command cannot complete."""target = os.path.abspath(target)ps_cmd = ("[System.Net.WebRequest]::DefaultWebProxy.Credentials = ""[System.Net.CredentialCache]::DefaultCredentials; "'(new-object System.Net.WebClient).DownloadFile("%(url)s", "%(target)s")'% locals())cmd = ['powershell','-Command',ps_cmd,]_clean_check(cmd, target)def has_powershell():"""Determine if Powershell is available."""if platform.system() != 'Windows':return Falsecmd = ['powershell', '-Command', 'echo test']with open(os.path.devnull, 'wb') as devnull:try:subprocess.check_call(cmd, stdout=devnull, stderr=devnull)except Exception:return Falsereturn True
download_file_powershell.viable = has_powershelldef download_file_curl(url, target):cmd = ['curl', url, '--location', '--silent', '--output', target]_clean_check(cmd, target)def has_curl():cmd = ['curl', '--version']with open(os.path.devnull, 'wb') as devnull:try:subprocess.check_call(cmd, stdout=devnull, stderr=devnull)except Exception:return Falsereturn True
download_file_curl.viable = has_curldef download_file_wget(url, target):cmd = ['wget', url, '--quiet', '--output-document', target]_clean_check(cmd, target)def has_wget():cmd = ['wget', '--version']with open(os.path.devnull, 'wb') as devnull:try:subprocess.check_call(cmd, stdout=devnull, stderr=devnull)except Exception:return Falsereturn True
download_file_wget.viable = has_wgetdef download_file_insecure(url, target):"""Use Python to download the file, without connection authentication."""src = urlopen(url)try:# Read all the data in one block.data = src.read()finally:src.close()# Write all the data in one block to avoid creating a partial file.with open(target, "wb") as dst:dst.write(data)
download_file_insecure.viable = lambda: Truedef get_best_downloader():downloaders = (download_file_powershell,download_file_curl,download_file_wget,download_file_insecure,)viable_downloaders = (dl for dl in downloaders if dl.viable())return next(viable_downloaders, None)def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,to_dir=DEFAULT_SAVE_DIR, delay=15,downloader_factory=get_best_downloader):"""Download setuptools from a specified location and return its filename.`version` should be a valid setuptools version number that is availableas an sdist for download under the `download_base` URL (which should endwith a '/'). `to_dir` is the directory where the egg will be downloaded.`delay` is the number of seconds to pause before an actual downloadattempt.``downloader_factory`` should be a function taking no arguments andreturning a function for downloading a URL to a target."""# making sure we use the absolute pathto_dir = os.path.abspath(to_dir)zip_name = "setuptools-%s.zip" % versionurl = download_base + zip_namesaveto = os.path.join(to_dir, zip_name)if not os.path.exists(saveto):  # Avoid repeated downloadslog.warn("Downloading %s", url)downloader = downloader_factory()downloader(url, saveto)return os.path.realpath(saveto)def _build_install_args(options):"""Build the arguments to 'python setup.py install' on the setuptools package.Returns list of command line arguments."""return ['--user'] if options.user_install else []def _parse_args():"""Parse the command line for options."""parser = optparse.OptionParser()parser.add_option('--user', dest='user_install', action='store_true', default=False,help='install in user site package')parser.add_option('--download-base', dest='download_base', metavar="URL",default=DEFAULT_URL,help='alternative URL from where to download the setuptools package')parser.add_option('--insecure', dest='downloader_factory', action='store_const',const=lambda: download_file_insecure, default=get_best_downloader,help='Use internal, non-validating downloader')parser.add_option('--version', help="Specify which version to download",default=DEFAULT_VERSION,)parser.add_option('--to-dir',help="Directory to save (and re-use) package",default=DEFAULT_SAVE_DIR,)options, args = parser.parse_args()# positional arguments are ignoredreturn optionsdef _download_args(options):"""Return args for download_setuptools function from cmdline args."""return dict(version=options.version,download_base=options.download_base,downloader_factory=options.downloader_factory,to_dir=options.to_dir,)def main():"""Install or upgrade setuptools and EasyInstall."""options = _parse_args()archive = download_setuptools(**_download_args(options))return _install(archive, _build_install_args(options))if __name__ == '__main__':sys.exit(main())


http://chatgpt.dhexx.cn/article/KZtP5Odm.shtml

相关文章

Setup Factory安装及程序安装包制作教程

阅读前提: 1.已制作好exe之类的可运行文件 一、软件安装 1、下载软件,这里以setup-factory 9.0.3.0.exe为例 下载地址:https://download.csdn.net/download/u010188178/10652645 2、安装该软件 3、汉化(如果有这个需要的话&a…

C#程序打包工具SetupFactory入门使用

SetupFactory是一款能够用于工程向导、自定义对话框、生成MD5序列化以及两百多个功能函数的脚步编辑器、授权支持等等众多的特性。总体来说使用起来比较简单,在这里俺就介绍一下如何打包C#项目,至于其他使用如果有时间后续俺会再介绍的。 在这里俺使用的…

安装包制作工具 SetupFactory 详解

安装包制作工具 SetupFactory 详解 转载自:https://www.cnblogs.com/lidabo/p/9809757.html Setup Factory 是一个强大的安装程序制作工具。提供了安装制作向导界面,即使你对安装制作不了解,也可以生成专业性质的安装程序。可建立快捷方式&…

高等数学学习笔记——第四十八讲——微分方程模型与基本概念

1. 问题引入——方程的出现是算术走向代数的重要标志(代数的任务就是解方程) 如,鸡兔同笼问题,用代数方程来解决就很简单。 2. 微分方程是一种数学模型。 数学建模:用数学的语言和方法,通过对实际问题的抽…

Python小白的数学建模课-09 微分方程模型

1. 微分方程 1.1 基本概念 微分方程是描述系统的状态随时间和空间演化的数学工具。物理中许多涉及变力的运动学、动力学问题,如空气的阻力为速度函数的落体运动等问题,很多可以用微分方程求解。微分方程在化学、工程学、经济学和人口统计等领域也有广泛…

微分方程模型(一)

人口模型: 量化人口增长的趋势 1.Malthus 模型 模型假设: (i)设x(t)表示t时刻的人口数,且x(t)连续可微。 (ii)人口的增长率r 是常数(增长率出生率—死亡率)。 &#…

【数学建模】9 微分方程模型建模方法及实例

目录 1 微分方程2 微分方程解决的主要问题3 微分方程模型4 微分方程解决问题的一般步骤第一步第二步第三步 5 微分方程举例6 经典的微分方程模型7 课后习题 1 微分方程 (1)概念:微分方程是含有函数及其导数的方程,如果方程组只含…

基于SEIR微分方程模型对疫情传播的简单预测

目录 一、模型的建立 传染病模型概念 模型假设 SEIR模型 模型中涉及的函数S(t)、E(t)、I(t)、R(t) 更改后的微分方程 二、模型的求解 三、模型的缺点 祝语 随着疫情的再次爆发,全国疫情防控再次进入紧张状态,疫情预测分析成为数学建模问题中的一个热点问…

【数学建模】14 微分方程模型求解方法

目录 1 MATLAB数值微积分2 微分方程数值解3 MATLAB求解常微分方程4 课后习题 1 MATLAB数值微积分 (1)差分与微分 • taylor 符号泰勒展开 • polyder 多项式求导 • diff 数值差分或符号求导 dx diff(x) %返回向量x的差分• gradient 数值梯度 Fx g…

数学建模-微分方程模型

引用:https://wenku.baidu.com/view/35ea8f8a2dc58bd63186bceb19e8b8f67c1cef82.html?rec_flagdefault&sxts1547780910061 微分方程建模是数学建模的重要方法,因为许多实际问题的数学描述将导致求解微分方程的定解问题。把形形色色的实际问题化成微…

18.微分方程模型

微分方程模型 1.应用matlab求解微分方程模型 2.例题 1) dsolve(Du1u^2,t)2) ydsolve(Dyexp(x),y(0)exp(1),x); ezplot(y,[-10,10])3) ydsolve(D2y4*Dy29*y0,y(0)0,Dy(0)15,x); ezplot(y,[1,4])4) [x,y,z]dsolve(Dx2*x-3*…

数学建模:微分方程模型— Python 求解

目录 例:使用显式欧拉法和四阶龙格库塔法计算Lorenz模型scipy.integrate.odeint 求解微分方程模型scipy.integrate.solve_ivp 求解微分方程模型 使用 Python 求常微分方程的数值求解通常是基于一阶方程进行的,高阶微分方程要化成一阶方程组。 例&#x…

数学建模预测方法之 微分方程模型

微分方程模型 短、中、长期的预测都适合。 反应事物内部规律及其内在关系,但由于方程的建立是以局部规律的独立性假定为基础,当作为长期预测时,误差较大,且微分方程的解比较难以得到。 具体案例 传染病的预测模型、经济增长&a…

常见的微分方程模型(1)

学习了几个常见的微分方程模型,比如传染病模型和经济增长模型 1.传染病模型 已知已感染人数(病人)的比例为 i(t) ,假设每个病人每天的有效接触的人数为,在一块封闭区域内,总人数为N ,健康人的…

微分方程模型的求解方法

微分方程模型的求解方法 在实际问题中经常需要寻求某个变量y随另一变量t的变化规律,yy(t)这个函数关系式常常不能直接求出。然而有时容易建立包含变量及导数在内的关系式,即建立变量能满足的微分方程,从而通过求解微分方程对所研究的问题进行解释说明。…

微分方程模型_天生一对,硬核微分方程与深度学习的「联姻」之路

微分方程真的能结合深度神经网络?真的能用来理解深度神经网络、推导神经网络架构、构建深度生成模型?我们将从鄂维南、董彬和陈天琦等研究者的工作中,窥探微分方程与深度学习联袂前行的路径。 近日,北京智源人工智能研究院开展了第…

微分方程模型——偏微分方程

1. 简介 微分方程:描述自然界中存在的物理现象和普遍规律。 常微分方程(ODE)偏微分方程(PDE) 偏微分方程理论: 物理/工程问题————翻译(建模)/物理工程规律————》数学问题…

数学建模——微分方程模型的求解

文章目录 微分方程的符号解法微分方程数值解法一些常用的微分方程模型(学习中,持续更新)Logistics模型传染病模型 本文介绍微分方程的求解,不介绍微分方程的建立方法 微分方程的符号解法 求解微分方程的符号解主要是依赖于Python…

微分方程模型_常微分方程模型简介

注:本文是刘然对常微分方程模型的简介 什么是常微分方程模型 常用的回归分析聚焦于直接建立响应变量和协变量之间的关系,之后根据建立的模型进行分析和预测,比如常见的线性回归模型:。 而如果我们感兴趣的变量是随时间变化的,那么还有另外一种常用的建模方式:建立变量与变…