#!/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 contextlib

from distutils import log

try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen

try:
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,) + args
return subprocess.call(args) == 0

def _install(archive_filename, install_args=()):
"""Install Setuptools."""
with archive_context(archive_filename):
# installing
log.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 2
return 2

def _build_egg(egg, archive_filename, to_dir):
"""Build Setuptools egg."""
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.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 self

def __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 directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
yield

finally:
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 setuptools
setuptools.bootstrap_install_from = egg

def 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 version
or 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_resources
pkg_resources.require("setuptools>=" + version)
# a suitable version is already installed
return
except ImportError:
# pkg_resources not available; setuptools is not installed; download
pass
except pkg_resources.DistributionNotFound:
# no version of setuptools was found; allow download
pass
except 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 is
unsafe 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. Please
install 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 = [
importer
for importer in sys.meta_path
if importer.__class__.__module__ != 'pkg_resources.extern'
]
del_modules = [
name for name in sys.modules
if 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)
raise

def 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 False
cmd = ['powershell', '-Command', 'echo test']
with open(os.path.devnull, 'wb') as devnull:
try:
subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
except Exception:
return False
return True
download_file_powershell.viable = has_powershell

def 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 False
return True
download_file_curl.viable = has_curl

def 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 False
return True
download_file_wget.viable = has_wget

def 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: True

def 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 available
as an sdist for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.

``downloader_factory`` should be a function taking no arguments and
returning a function for downloading a URL to a target.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
zip_name = "setuptools-%s.zip" % version
url = download_base + zip_name
saveto = os.path.join(to_dir, zip_name)
if not os.path.exists(saveto): # Avoid repeated downloads
log.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 ignored
return options

def _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())

添加setuptools脚本的更多相关文章

  1. 在html中添加script脚本的方法和注意事项

    在html中添加script脚本有两种方法,直接将javascript代码添加到html中与添加外部js文件,这两种方法都比较常用,大家可以根据自己需要自由选择 在html中添加<script& ...

  2. Linux下添加shell脚本使得nginx日志每天定时切割压缩

    Linux下添加shell脚本使得nginx日志每天定时切割压缩一 简介 对于nginx的日志文件,特别是access日志,如果我们不做任何处理的话,最后这个文件将会变得非常庞大 这时,无论是出现异常 ...

  3. Unity脚本自动添加注释脚本及排版格式

    Unity脚本自动添加注释脚本及头部注释排版格式 公司开发项目,需要声明版权所有,,,,标注公司名,作者,时间,项目名称及描述等等. 自己总结实现的现成脚本及头部注释排版文本,添加到模版即可. 文件不 ...

  4. arcgis python arcpy add data script添加数据脚本

    arcgis python arcpy add data script添加数据脚本mxd = arcpy.mapping.MapDocument("CURRENT")... df ...

  5. ASP.NET 网页动态添加客户端脚本

    在System.Web.UI.Page类中包含了RegisterStarupScript()和RegisterClientScriptBlock()两个方法,使用这两个方法可以实现向Web页面动态添加 ...

  6. 工程师技术(五):Shell脚本的编写及测试、重定向输出的应用、使用特殊变量、编写一个判断脚本、编写一个批量添加用户脚本

    一.Shell脚本的编写及测 目标: 本例要求两个简单的Shell脚本程序,任务目标如下: 1> 编写一个面世问候 /root/helloworld.sh 脚本,执行后显示出一段话“Hello ...

  7. shell编写一个批量添加用户脚本

                                                          shell编写一个批量添加用户脚本 5.1问题 本例要求在虚拟机server0上创建/roo ...

  8. Unity3D开发入门教程(三)——添加启动脚本

    五邑隐侠,本名关健昌,12年游戏生涯. 本教程以 Unity 3D + VS Code + C# + tolua 为例. 一.启动脚本 第一篇 "搭建开发环境",在 "配 ...

  9. VSCode添加Sciter脚本Tiscript高亮支持

    Sciter中的Tiscript脚本不是标准的Javascript,是对Javascript的扩展.所以在常用的编辑器和IDE上对于高亮的支持很不好. 不过在Sciter论坛中找到了在VSCode上的 ...

随机推荐

  1. CouldnotcreatetheJavaVirtualMachine/1709

    Section A: symptom --------------------   SWPM1024 S/4hana 1709 安装过程中遇到error, 错误提示错误信息在/tmp/sapinst_ ...

  2. 【函数】SAS宏的特殊字符引用【转载】

    原文地址  :  http://blog.chinaunix.net/uid-675476-id-2076827.html 在SAS宏中,字符串是用双引号括起来的,但如果字符串中要包含双引号或百分号等 ...

  3. Maven父工程

    1.创建Maven工程时 Packaging 选项为 pom 2.父工程目录结构只有pom.xml(父工程不进行编码) 3.需要的依赖信息在父工程中定义,子模块继承 5.将各个子模块聚合到一起 6.将 ...

  4. 白鹭引擎 - 碰撞检测 ( hitTestPoint )

    1, 矩形碰撞检测 class Main extends egret.DisplayObjectContainer { /** * Main 类构造器, 初始化的时候自动执行, ( 子类的构造函数必须 ...

  5. Node Koa2 完整教程

    请移步 http://cnodejs.org/topic/58ac640e7872ea0864fedf90

  6. Redis 主从复制, 读写分离

    1: 是什么? 2: 经常是配置从库, 不配置主库 3.1: 每次与 master 断开之后都要从连, 除非你配置了redis.conf 3.2: 获取当前redis 服务信息 => info ...

  7. react-native android 报错 error calling Appregistry.runApplication

    解决了权限问题以为就没问题了,但是进来就红屏了,报错信息如下: 解决了,懒得截图了 error calling Appregistry.runApplication 这个问题也找了很久,开始找到 ht ...

  8. C语言中的__LINE__宏

    在C语言中,有这么四个预定义的宏: 当前文件: __FILE__ 当前行号: __LINE__ 当前日期: __DATE__ 当前时间: __TIME__ 这4个宏在代码编译的时候,由编译器替换成实际 ...

  9. VC 字符串转化和分割

    原文:点击这里. 备忘:为了适用于Unicode环境,要养成使用_T()宏的习惯 1.格式化字符串 CString s;s.Format(_T("The num is %d."), ...

  10. 用U盘制作启动盘后空间变小的恢复方法

    先把u盘插好, 运行cmd(按住键盘左下角第二个windows键的同时按R), 输入diskpart,回车, (此时可以再输入list disk,回车,能看到这台电脑的所有磁盘大致情况,u盘一般是磁盘 ...