1. #!/usr/bin/env python
  2. """Bootstrap setuptools installation
  3.  
  4. To use setuptools in your package's setup.py, include this
  5. file in the same directory and add this to the top of your setup.py::
  6.  
  7. from ez_setup import use_setuptools
  8. use_setuptools()
  9.  
  10. To require a specific version of setuptools, set a download
  11. mirror, or use an alternate download directory, simply supply
  12. the appropriate options to ``use_setuptools()``.
  13.  
  14. This file can also be run as a script to install or upgrade setuptools.
  15. """
  16. import os
  17. import shutil
  18. import sys
  19. import tempfile
  20. import zipfile
  21. import optparse
  22. import subprocess
  23. import platform
  24. import textwrap
  25. import contextlib
  26.  
  27. from distutils import log
  28.  
  29. try:
  30. from urllib.request import urlopen
  31. except ImportError:
  32. from urllib2 import urlopen
  33.  
  34. try:
  35. from site import USER_SITE
  36. except ImportError:
  37. USER_SITE = None
  38.  
  39. DEFAULT_VERSION = "5.4.1"
  40. DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/"
  41.  
  42. def _python_cmd(*args):
  43. """
  44. Return True if the command succeeded.
  45. """
  46. args = (sys.executable,) + args
  47. return subprocess.call(args) == 0
  48.  
  49. def _install(archive_filename, install_args=()):
  50. with archive_context(archive_filename):
  51. # installing
  52. log.warn('Installing Setuptools')
  53. if not _python_cmd('setup.py', 'install', *install_args):
  54. log.warn('Something went wrong during the installation.')
  55. log.warn('See the error message above.')
  56. # exitcode will be 2
  57. return 2
  58.  
  59. def _build_egg(egg, archive_filename, to_dir):
  60. with archive_context(archive_filename):
  61. # building an egg
  62. log.warn('Building a Setuptools egg in %s', to_dir)
  63. _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
  64. # returning the result
  65. log.warn(egg)
  66. if not os.path.exists(egg):
  67. raise IOError('Could not build the egg.')
  68.  
  69. class ContextualZipFile(zipfile.ZipFile):
  70. """
  71. Supplement ZipFile class to support context manager for Python 2.6
  72. """
  73.  
  74. def __enter__(self):
  75. return self
  76.  
  77. def __exit__(self, type, value, traceback):
  78. self.close()
  79.  
  80. def __new__(cls, *args, **kwargs):
  81. """
  82. Construct a ZipFile or ContextualZipFile as appropriate
  83. """
  84. if hasattr(zipfile.ZipFile, '__exit__'):
  85. return zipfile.ZipFile(*args, **kwargs)
  86. return super(ContextualZipFile, cls).__new__(cls)
  87.  
  88. @contextlib.contextmanager
  89. def archive_context(filename):
  90. # extracting the archive
  91. tmpdir = tempfile.mkdtemp()
  92. log.warn('Extracting in %s', tmpdir)
  93. old_wd = os.getcwd()
  94. try:
  95. os.chdir(tmpdir)
  96. with ContextualZipFile(filename) as archive:
  97. archive.extractall()
  98.  
  99. # going in the directory
  100. subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
  101. os.chdir(subdir)
  102. log.warn('Now working in %s', subdir)
  103. yield
  104.  
  105. finally:
  106. os.chdir(old_wd)
  107. shutil.rmtree(tmpdir)
  108.  
  109. def _do_download(version, download_base, to_dir, download_delay):
  110. egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
  111. % (version, sys.version_info[0], sys.version_info[1]))
  112. if not os.path.exists(egg):
  113. archive = download_setuptools(version, download_base,
  114. to_dir, download_delay)
  115. _build_egg(egg, archive, to_dir)
  116. sys.path.insert(0, egg)
  117.  
  118. # Remove previously-imported pkg_resources if present (see
  119. # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
  120. if 'pkg_resources' in sys.modules:
  121. del sys.modules['pkg_resources']
  122.  
  123. import setuptools
  124. setuptools.bootstrap_install_from = egg
  125.  
  126. def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
  127. to_dir=os.curdir, download_delay=15):
  128. to_dir = os.path.abspath(to_dir)
  129. rep_modules = 'pkg_resources', 'setuptools'
  130. imported = set(sys.modules).intersection(rep_modules)
  131. try:
  132. import pkg_resources
  133. except ImportError:
  134. return _do_download(version, download_base, to_dir, download_delay)
  135. try:
  136. pkg_resources.require("setuptools>=" + version)
  137. return
  138. except pkg_resources.DistributionNotFound:
  139. return _do_download(version, download_base, to_dir, download_delay)
  140. except pkg_resources.VersionConflict as VC_err:
  141. if imported:
  142. msg = textwrap.dedent("""
  143. The required version of setuptools (>={version}) is not available,
  144. and can't be installed while this script is running. Please
  145. install a more recent version first, using
  146. 'easy_install -U setuptools'.
  147.  
  148. (Currently using {VC_err.args[0]!r})
  149. """).format(VC_err=VC_err, version=version)
  150. sys.stderr.write(msg)
  151. sys.exit(2)
  152.  
  153. # otherwise, reload ok
  154. del pkg_resources, sys.modules['pkg_resources']
  155. return _do_download(version, download_base, to_dir, download_delay)
  156.  
  157. def _clean_check(cmd, target):
  158. """
  159. Run the command to download target. If the command fails, clean up before
  160. re-raising the error.
  161. """
  162. try:
  163. subprocess.check_call(cmd)
  164. except subprocess.CalledProcessError:
  165. if os.access(target, os.F_OK):
  166. os.unlink(target)
  167. raise
  168.  
  169. def download_file_powershell(url, target):
  170. """
  171. Download the file at url to target using Powershell (which will validate
  172. trust). Raise an exception if the command cannot complete.
  173. """
  174. target = os.path.abspath(target)
  175. ps_cmd = (
  176. "[System.Net.WebRequest]::DefaultWebProxy.Credentials = "
  177. "[System.Net.CredentialCache]::DefaultCredentials; "
  178. "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)"
  179. % vars()
  180. )
  181. cmd = [
  182. 'powershell',
  183. '-Command',
  184. ps_cmd,
  185. ]
  186. _clean_check(cmd, target)
  187.  
  188. def has_powershell():
  189. if platform.system() != 'Windows':
  190. return False
  191. cmd = ['powershell', '-Command', 'echo test']
  192. with open(os.path.devnull, 'wb') as devnull:
  193. try:
  194. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  195. except Exception:
  196. return False
  197. return True
  198.  
  199. download_file_powershell.viable = has_powershell
  200.  
  201. def download_file_curl(url, target):
  202. cmd = ['curl', url, '--silent', '--output', target]
  203. _clean_check(cmd, target)
  204.  
  205. def has_curl():
  206. cmd = ['curl', '--version']
  207. with open(os.path.devnull, 'wb') as devnull:
  208. try:
  209. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  210. except Exception:
  211. return False
  212. return True
  213.  
  214. download_file_curl.viable = has_curl
  215.  
  216. def download_file_wget(url, target):
  217. cmd = ['wget', url, '--quiet', '--output-document', target]
  218. _clean_check(cmd, target)
  219.  
  220. def has_wget():
  221. cmd = ['wget', '--version']
  222. with open(os.path.devnull, 'wb') as devnull:
  223. try:
  224. subprocess.check_call(cmd, stdout=devnull, stderr=devnull)
  225. except Exception:
  226. return False
  227. return True
  228.  
  229. download_file_wget.viable = has_wget
  230.  
  231. def download_file_insecure(url, target):
  232. """
  233. Use Python to download the file, even though it cannot authenticate the
  234. connection.
  235. """
  236. src = urlopen(url)
  237. try:
  238. # Read all the data in one block.
  239. data = src.read()
  240. finally:
  241. src.close()
  242.  
  243. # Write all the data in one block to avoid creating a partial file.
  244. with open(target, "wb") as dst:
  245. dst.write(data)
  246.  
  247. download_file_insecure.viable = lambda: True
  248.  
  249. def get_best_downloader():
  250. downloaders = (
  251. download_file_powershell,
  252. download_file_curl,
  253. download_file_wget,
  254. download_file_insecure,
  255. )
  256. viable_downloaders = (dl for dl in downloaders if dl.viable())
  257. return next(viable_downloaders, None)
  258.  
  259. def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
  260. to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader):
  261. """
  262. Download setuptools from a specified location and return its filename
  263.  
  264. `version` should be a valid setuptools version number that is available
  265. as an egg for download under the `download_base` URL (which should end
  266. with a '/'). `to_dir` is the directory where the egg will be downloaded.
  267. `delay` is the number of seconds to pause before an actual download
  268. attempt.
  269.  
  270. ``downloader_factory`` should be a function taking no arguments and
  271. returning a function for downloading a URL to a target.
  272. """
  273. # making sure we use the absolute path
  274. to_dir = os.path.abspath(to_dir)
  275. zip_name = "setuptools-%s.zip" % version
  276. url = download_base + zip_name
  277. saveto = os.path.join(to_dir, zip_name)
  278. if not os.path.exists(saveto): # Avoid repeated downloads
  279. log.warn("Downloading %s", url)
  280. downloader = downloader_factory()
  281. downloader(url, saveto)
  282. return os.path.realpath(saveto)
  283.  
  284. def _build_install_args(options):
  285. """
  286. Build the arguments to 'python setup.py install' on the setuptools package
  287. """
  288. return ['--user'] if options.user_install else []
  289.  
  290. def _parse_args():
  291. """
  292. Parse the command line for options
  293. """
  294. parser = optparse.OptionParser()
  295. parser.add_option(
  296. '--user', dest='user_install', action='store_true', default=False,
  297. help='install in user site package (requires Python 2.6 or later)')
  298. parser.add_option(
  299. '--download-base', dest='download_base', metavar="URL",
  300. default=DEFAULT_URL,
  301. help='alternative URL from where to download the setuptools package')
  302. parser.add_option(
  303. '--insecure', dest='downloader_factory', action='store_const',
  304. const=lambda: download_file_insecure, default=get_best_downloader,
  305. help='Use internal, non-validating downloader'
  306. )
  307. parser.add_option(
  308. '--version', help="Specify which version to download",
  309. default=DEFAULT_VERSION,
  310. )
  311. options, args = parser.parse_args()
  312. # positional arguments are ignored
  313. return options
  314.  
  315. def main():
  316. """Install or upgrade setuptools and EasyInstall"""
  317. options = _parse_args()
  318. archive = download_setuptools(
  319. version=options.version,
  320. download_base=options.download_base,
  321. downloader_factory=options.downloader_factory,
  322. )
  323. return _install(archive, _build_install_args(options))
  324.  
  325. if __name__ == '__main__':
  326. sys.exit(main())

python pip ez_setup.py的更多相关文章

  1. python 装 ez_setup.py 出错

    python 装 ez_setup.py出错setuptools,pip,install,UnicodeDecodeError: 'ascii' codec can't decode byte.解决: ...

  2. python 安装 ez_setup.py出现的问题及解决办法

    试了网上好几个解决办法. 下面这个办法是最对我胃口的.  ~~~~~~~~~~~~~~~~ 安装ez_setup.py时出现了这个问题: UnicodeDecodeError: 'ascii' cod ...

  3. ez_setup.py(安装python下setuptools用)

    #!python"""Bootstrap setuptools installation If you want to use setuptools in your pa ...

  4. 安装python File "/usr/bin/pip", line 11, in <module> sys.exit(main()) File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main locale.setlocale(locale.LC_ALL, '') File "/u

      $ uname -a Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU ...

  5. python pip包管理器安装

    下载   http://peak.telecommunity.com/dist/ez_setup.py 执行:python ez_setup.py 下载:  http://pypi.python.or ...

  6. macosx 10.11 python pip install 出现错误OSError: [Errno 1] Operation not permitted:

    Exception: Traceback (most recent call last): File , in main status = self.run(options, args) File , ...

  7. Python pip – error: invalid command ‘bdist_wheel’

    原文@http://software-engineer.gatsbylee.com/python-pip-error-invalid-command-bdist_wheel/ Python pip – ...

  8. python pip安装模块提示错误failed to create process

    python pip安装模块提示错误failed to create process 原因: 报这个错误的原因,是因为python的目录名称或位置发生改动. 解决办法: 1.找到修改python所在的 ...

  9. python 利用 setup.py 手动安装第三方类库

    python 利用 setup.py 手动安装第三方类库 由于我在mac使用时,装了python3,默认有python2的环境,使用 pip 安装第三方类库时,老是安装到 python2的环境上: 在 ...

随机推荐

  1. Tomcat翻译--The Host Container

    原文:http://tomcat.apache.org/tomcat-7.0-doc/config/host.html Introduction(介绍) The Host element repres ...

  2. mac下用brew安装mongodb

    分享到:QQ空间新浪微博腾讯微博人人网微信 mac 下安装mongoDB一般俩种方法. (1)下载源码,解压,编译,配置,启动 比较艰难的一种模式. (2)brew install mongodb , ...

  3. vector map迭代器失效解决方案

    vector : iter = container.erase(iter);    //erase的返回值是删除元素下一个元素的迭代器 vector<int>::iterator it = ...

  4. LeetCode 314. Binary Tree Vertical Order Traversal

    原题链接在这里:https://leetcode.com/problems/binary-tree-vertical-order-traversal/ 题目: Given a binary tree, ...

  5. Js中的prototype的用法二

    用过JavaScript的同学们肯定都对prototype如雷贯耳,但是这究竟是个什么东西却让初学者莫衷一是,只知道函数都会有一个prototype属性,可以为其添加函数供实例访问,其它的就不清楚了, ...

  6. virtualvm一次插件安装想到的

    在麒麟操作系统visualvm安装插件失败,因为使用的内网,所以在官网下载了插件到本地:因为本地安装的jdk1.6,为了享受jdk1.8,在visualvm文件中增加了对于jdk1.8的引用: exp ...

  7. BZOJ2002:[HNOI2010]弹飞绵羊

    浅谈分块:https://www.cnblogs.com/AKMer/p/10369816.html 题目传送门:https://lydsy.com/JudgeOnline/problem.php?i ...

  8. SPI编程1:用户空间的读写操作

    spi_device 虽然用户空间不需要直接用到spi_device结构体,但是这个结构体和用户空间的程序有密切的关系,理解它的成员有助于理解SPI设备节点的IOCTL命令,所以首先来介绍它.在内核中 ...

  9. spring学习十二 application/x-www-form-urlencoded还是application/json

    application/x-www-form-urlencoded还是application/json get. POST 用哪种格式? 后台如何得到这些值? 如何用ajax  或者是 postman ...

  10. 2015.3.12Arinc424 Tools中SiniArincCls.csParserFile(string sFile)函数正则表达式理解

    原文: string RegEx1 = @"(\[ITEM\]\s*=[\S\s]*?(?=\[ITEM\])|\[ITEM\]\s*=[\S\s]*)";//用来识别主记录和后续 ...