• ubuntu 12.04 安装pip等命令安装模块失败


    参考文章:http://www.gm100861.com/816.html

    python2和python3的变化太大了,在一个系统中现在都是两个版本都安装了,刚开始学习python有种无所是从的感觉,想使用pip这个模块安装工具,就因为多版本python的问题报错:

    1 # pip
    2 Traceback (most recent call last):
    3   File "/usr/bin/pip", line 5, in <module>
    4     from pkg_resources import load_entry_point
    5 ImportError: No module named pkg_resources

    问题:

      在ubunu 12.04 下面有多个python版本,所以在使用pip的时候会导致报错

    1 # python
    2 python                python2.7-dbg         python2-dbg-config    python3mu
    3 python2               python2.7-dbg-config  python3               python-config
    4 python2.7             python2-config        python3.2             python-dbg
    5 python2.7-config      python2-dbg           python3.2mu           python-dbg-config

    解决:

    1 # curl -O http://python-distribute.org/distribute_setup.py
    2 # /usr/local/pyton2.7/bin/python distribute_setup.py

    使用新版本的python来运行这个脚本,这个会自动安装出来一个easy_install,然后使用这个新的easy_install来安装pip就可以了!

    1 # /usr/local/python/bin/easy_install pip
    2 # /usr/local/python/bin/pip -V
    3 pip 1.4.1 from /usr/local/python/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg (python 2.7)

    安装生成的所有二进制文件,都是在你的PYTHON_HOME/bin/,因为我的是安装在/usr/local/python/,所以命令都在这里,以后再调用pip要使用绝对路径,或者做链接!

    1 ln -s /usr/local/python2.7/bin/pip /usr/bin/pip

    2.7的模块是在以下目录

    /usr/local/python/lib/python2.7/site-packages/

    安装 mysql模块

     

    1 easy_install MySQL-python

    NOTE:

        按照这个方法也可以为python3安装模块,但是还没有好好的了解的python3所以这块内容就先不管了!

    附:脚本的原文

      1 #!python
      2 """Bootstrap distribute installation
      3  
      4 If you want to use setuptools in your package's setup.py, just include this
      5 file in the same directory with it, and add this to the top of your setup.py::
      6  
      7     from distribute_setup import use_setuptools
      8     use_setuptools()
      9  
     10 If you want to require a specific version of setuptools, set a download
     11 mirror, or use an alternate download directory, you can do so by supplying
     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 time
     20 import fnmatch
     21 import tempfile
     22 import tarfile
     23 import optparse
     24  
     25 from distutils import log
     26  
     27 try:
     28     from site import USER_SITE
     29 except ImportError:
     30     USER_SITE = None
     31  
     32 try:
     33     import subprocess
     34  
     35     def _python_cmd(*args):
     36         args = (sys.executable,) + args
     37         return subprocess.call(args) == 0
     38  
     39 except ImportError:
     40     # will be used for python 2.3
     41     def _python_cmd(*args):
     42         args = (sys.executable,) + args
     43         # quoting arguments if windows
     44         if sys.platform == 'win32':
     45             def quote(arg):
     46                 if ' ' in arg:
     47                     return '"%s"' % arg
     48                 return arg
     49             args = [quote(arg) for arg in args]
     50         return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
     51  
     52 DEFAULT_VERSION = "0.6.49"
     53 DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
     54 SETUPTOOLS_FAKED_VERSION = "0.6c11"
     55  
     56 SETUPTOOLS_PKG_INFO = """
     57 Metadata-Version: 1.0
     58 Name: setuptools
     59 Version: %s
     60 Summary: xxxx
     61 Home-page: xxx
     62 Author: xxx
     63 Author-email: xxx
     64 License: xxx
     65 Description: xxx
     66 """ % SETUPTOOLS_FAKED_VERSION
     67  
     68 def _install(tarball, install_args=()):
     69     # extracting the tarball
     70     tmpdir = tempfile.mkdtemp()
     71     log.warn('Extracting in %s', tmpdir)
     72     old_wd = os.getcwd()
     73     try:
     74         os.chdir(tmpdir)
     75         tar = tarfile.open(tarball)
     76         _extractall(tar)
     77         tar.close()
     78  
     79         # going in the directory
     80         subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
     81         os.chdir(subdir)
     82         log.warn('Now working in %s', subdir)
     83  
     84         # installing
     85         log.warn('Installing Distribute')
     86         if not _python_cmd('setup.py', 'install', *install_args):
     87             log.warn('Something went wrong during the installation.')
     88             log.warn('See the error message above.')
     89             # exitcode will be 2
     90             return 2
     91     finally:
     92         os.chdir(old_wd)
     93         shutil.rmtree(tmpdir)
     94  
     95 def _build_egg(egg, tarball, to_dir):
     96     # extracting the tarball
     97     tmpdir = tempfile.mkdtemp()
     98     log.warn('Extracting in %s', tmpdir)
     99     old_wd = os.getcwd()
    100     try:
    101         os.chdir(tmpdir)
    102         tar = tarfile.open(tarball)
    103         _extractall(tar)
    104         tar.close()
    105  
    106         # going in the directory
    107         subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
    108         os.chdir(subdir)
    109         log.warn('Now working in %s', subdir)
    110  
    111         # building an egg
    112         log.warn('Building a Distribute egg in %s', to_dir)
    113         _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
    114  
    115     finally:
    116         os.chdir(old_wd)
    117         shutil.rmtree(tmpdir)
    118     # returning the result
    119     log.warn(egg)
    120     if not os.path.exists(egg):
    121         raise IOError('Could not build the egg.')
    122  
    123 def _do_download(version, download_base, to_dir, download_delay):
    124     egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
    125                        % (version, sys.version_info[0], sys.version_info[1]))
    126     if not os.path.exists(egg):
    127         tarball = download_setuptools(version, download_base,
    128                                       to_dir, download_delay)
    129         _build_egg(egg, tarball, to_dir)
    130     sys.path.insert(0, egg)
    131     import setuptools
    132     setuptools.bootstrap_install_from = egg
    133  
    134 def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
    135                    to_dir=os.curdir, download_delay=15, no_fake=True):
    136     # making sure we use the absolute path
    137     to_dir = os.path.abspath(to_dir)
    138     was_imported = 'pkg_resources' in sys.modules or 
    139         'setuptools' in sys.modules
    140     try:
    141         try:
    142             import pkg_resources
    143  
    144             # Setuptools 0.7b and later is a suitable (and preferable)
    145             # substitute for any Distribute version.
    146             try:
    147                 pkg_resources.require("setuptools>=0.7b")
    148                 return
    149             except (pkg_resources.DistributionNotFound,
    150                     pkg_resources.VersionConflict):
    151                 pass
    152  
    153             if not hasattr(pkg_resources, '_distribute'):
    154                 if not no_fake:
    155                     _fake_setuptools()
    156                 raise ImportError
    157         except ImportError:
    158             return _do_download(version, download_base, to_dir, download_delay)
    159         try:
    160             pkg_resources.require("distribute>=" + version)
    161             return
    162         except pkg_resources.VersionConflict:
    163             e = sys.exc_info()[1]
    164             if was_imported:
    165                 sys.stderr.write(
    166                 "The required version of distribute (>=%s) is not available,
    "
    167                 "and can't be installed while this script is running. Please
    "
    168                 "install a more recent version first, using
    "
    169                 "'easy_install -U distribute'."
    170                 "
    
    (Currently using %r)
    " % (version, e.args[0]))
    171                 sys.exit(2)
    172             else:
    173                 del pkg_resources, sys.modules['pkg_resources']    # reload ok
    174                 return _do_download(version, download_base, to_dir,
    175                                     download_delay)
    176         except pkg_resources.DistributionNotFound:
    177             return _do_download(version, download_base, to_dir,
    178                                 download_delay)
    179     finally:
    180         if not no_fake:
    181             _create_fake_setuptools_pkg_info(to_dir)
    182  
    183 def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
    184                         to_dir=os.curdir, delay=15):
    185     """Download distribute from a specified location and return its filename
    186  
    187     `version` should be a valid distribute version number that is available
    188     as an egg for download under the `download_base` URL (which should end
    189     with a '/'). `to_dir` is the directory where the egg will be downloaded.
    190     `delay` is the number of seconds to pause before an actual download
    191     attempt.
    192     """
    193     # making sure we use the absolute path
    194     to_dir = os.path.abspath(to_dir)
    195     try:
    196         from urllib.request import urlopen
    197     except ImportError:
    198         from urllib2 import urlopen
    199     tgz_name = "distribute-%s.tar.gz" % version
    200     url = download_base + tgz_name
    201     saveto = os.path.join(to_dir, tgz_name)
    202     src = dst = None
    203     if not os.path.exists(saveto):  # Avoid repeated downloads
    204         try:
    205             log.warn("Downloading %s", url)
    206             src = urlopen(url)
    207             # Read/write all in one block, so we don't create a corrupt file
    208             # if the download is interrupted.
    209             data = src.read()
    210             dst = open(saveto, "wb")
    211             dst.write(data)
    212         finally:
    213             if src:
    214                 src.close()
    215             if dst:
    216                 dst.close()
    217     return os.path.realpath(saveto)
    218  
    219 def _no_sandbox(function):
    220     def __no_sandbox(*args, **kw):
    221         try:
    222             from setuptools.sandbox import DirectorySandbox
    223             if not hasattr(DirectorySandbox, '_old'):
    224                 def violation(*args):
    225                     pass
    226                 DirectorySandbox._old = DirectorySandbox._violation
    227                 DirectorySandbox._violation = violation
    228                 patched = True
    229             else:
    230                 patched = False
    231         except ImportError:
    232             patched = False
    233  
    234         try:
    235             return function(*args, **kw)
    236         finally:
    237             if patched:
    238                 DirectorySandbox._violation = DirectorySandbox._old
    239                 del DirectorySandbox._old
    240  
    241     return __no_sandbox
    242  
    243 def _patch_file(path, content):
    244     """Will backup the file then patch it"""
    245     f = open(path)
    246     existing_content = f.read()
    247     f.close()
    248     if existing_content == content:
    249         # already patched
    250         log.warn('Already patched.')
    251         return False
    252     log.warn('Patching...')
    253     _rename_path(path)
    254     f = open(path, 'w')
    255     try:
    256         f.write(content)
    257     finally:
    258         f.close()
    259     return True
    260  
    261 _patch_file = _no_sandbox(_patch_file)
    262  
    263 def _same_content(path, content):
    264     f = open(path)
    265     existing_content = f.read()
    266     f.close()
    267     return existing_content == content
    268  
    269 def _rename_path(path):
    270     new_name = path + '.OLD.%s' % time.time()
    271     log.warn('Renaming %s to %s', path, new_name)
    272     os.rename(path, new_name)
    273     return new_name
    274  
    275 def _remove_flat_installation(placeholder):
    276     if not os.path.isdir(placeholder):
    277         log.warn('Unkown installation at %s', placeholder)
    278         return False
    279     found = False
    280     for file in os.listdir(placeholder):
    281         if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
    282             found = True
    283             break
    284     if not found:
    285         log.warn('Could not locate setuptools*.egg-info')
    286         return
    287  
    288     log.warn('Moving elements out of the way...')
    289     pkg_info = os.path.join(placeholder, file)
    290     if os.path.isdir(pkg_info):
    291         patched = _patch_egg_dir(pkg_info)
    292     else:
    293         patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
    294  
    295     if not patched:
    296         log.warn('%s already patched.', pkg_info)
    297         return False
    298     # now let's move the files out of the way
    299     for element in ('setuptools', 'pkg_resources.py', 'site.py'):
    300         element = os.path.join(placeholder, element)
    301         if os.path.exists(element):
    302             _rename_path(element)
    303         else:
    304             log.warn('Could not find the %s element of the '
    305                      'Setuptools distribution', element)
    306     return True
    307  
    308 _remove_flat_installation = _no_sandbox(_remove_flat_installation)
    309  
    310 def _after_install(dist):
    311     log.warn('After install bootstrap.')
    312     placeholder = dist.get_command_obj('install').install_purelib
    313     _create_fake_setuptools_pkg_info(placeholder)
    314  
    315 def _create_fake_setuptools_pkg_info(placeholder):
    316     if not placeholder or not os.path.exists(placeholder):
    317         log.warn('Could not find the install location')
    318         return
    319     pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
    320     setuptools_file = 'setuptools-%s-py%s.egg-info' % 
    321             (SETUPTOOLS_FAKED_VERSION, pyver)
    322     pkg_info = os.path.join(placeholder, setuptools_file)
    323     if os.path.exists(pkg_info):
    324         log.warn('%s already exists', pkg_info)
    325         return
    326  
    327     log.warn('Creating %s', pkg_info)
    328     try:
    329         f = open(pkg_info, 'w')
    330     except EnvironmentError:
    331         log.warn("Don't have permissions to write %s, skipping", pkg_info)
    332         return
    333     try:
    334         f.write(SETUPTOOLS_PKG_INFO)
    335     finally:
    336         f.close()
    337  
    338     pth_file = os.path.join(placeholder, 'setuptools.pth')
    339     log.warn('Creating %s', pth_file)
    340     f = open(pth_file, 'w')
    341     try:
    342         f.write(os.path.join(os.curdir, setuptools_file))
    343     finally:
    344         f.close()
    345  
    346 _create_fake_setuptools_pkg_info = _no_sandbox(
    347     _create_fake_setuptools_pkg_info
    348 )
    349  
    350 def _patch_egg_dir(path):
    351     # let's check if it's already patched
    352     pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
    353     if os.path.exists(pkg_info):
    354         if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
    355             log.warn('%s already patched.', pkg_info)
    356             return False
    357     _rename_path(path)
    358     os.mkdir(path)
    359     os.mkdir(os.path.join(path, 'EGG-INFO'))
    360     pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
    361     f = open(pkg_info, 'w')
    362     try:
    363         f.write(SETUPTOOLS_PKG_INFO)
    364     finally:
    365         f.close()
    366     return True
    367  
    368 _patch_egg_dir = _no_sandbox(_patch_egg_dir)
    369  
    370 def _before_install():
    371     log.warn('Before install bootstrap.')
    372     _fake_setuptools()
    373  
    374 def _under_prefix(location):
    375     if 'install' not in sys.argv:
    376         return True
    377     args = sys.argv[sys.argv.index('install') + 1:]
    378     for index, arg in enumerate(args):
    379         for option in ('--root', '--prefix'):
    380             if arg.startswith('%s=' % option):
    381                 top_dir = arg.split('root=')[-1]
    382                 return location.startswith(top_dir)
    383             elif arg == option:
    384                 if len(args) > index:
    385                     top_dir = args[index + 1]
    386                     return location.startswith(top_dir)
    387         if arg == '--user' and USER_SITE is not None:
    388             return location.startswith(USER_SITE)
    389     return True
    390  
    391 def _fake_setuptools():
    392     log.warn('Scanning installed packages')
    393     try:
    394         import pkg_resources
    395     except ImportError:
    396         # we're cool
    397         log.warn('Setuptools or Distribute does not seem to be installed.')
    398         return
    399     ws = pkg_resources.working_set
    400     try:
    401         setuptools_dist = ws.find(
    402             pkg_resources.Requirement.parse('setuptools', replacement=False)
    403             )
    404     except TypeError:
    405         # old distribute API
    406         setuptools_dist = ws.find(
    407             pkg_resources.Requirement.parse('setuptools')
    408         )
    409  
    410     if setuptools_dist is None:
    411         log.warn('No setuptools distribution found')
    412         return
    413     # detecting if it was already faked
    414     setuptools_location = setuptools_dist.location
    415     log.warn('Setuptools installation detected at %s', setuptools_location)
    416  
    417     # if --root or --preix was provided, and if
    418     # setuptools is not located in them, we don't patch it
    419     if not _under_prefix(setuptools_location):
    420         log.warn('Not patching, --root or --prefix is installing Distribute'
    421                  ' in another location')
    422         return
    423  
    424     # let's see if its an egg
    425     if not setuptools_location.endswith('.egg'):
    426         log.warn('Non-egg installation')
    427         res = _remove_flat_installation(setuptools_location)
    428         if not res:
    429             return
    430     else:
    431         log.warn('Egg installation')
    432         pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
    433         if (os.path.exists(pkg_info) and
    434             _same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
    435             log.warn('Already patched.')
    436             return
    437         log.warn('Patching...')
    438         # let's create a fake egg replacing setuptools one
    439         res = _patch_egg_dir(setuptools_location)
    440         if not res:
    441             return
    442     log.warn('Patching complete.')
    443     _relaunch()
    444  
    445 def _relaunch():
    446     log.warn('Relaunching...')
    447     # we have to relaunch the process
    448     # pip marker to avoid a relaunch bug
    449     _cmd1 = ['-c', 'install', '--single-version-externally-managed']
    450     _cmd2 = ['-c', 'install', '--record']
    451     if sys.argv[:3] == _cmd1 or sys.argv[:3] == _cmd2:
    452         sys.argv[0] = 'setup.py'
    453     args = [sys.executable] + sys.argv
    454     sys.exit(subprocess.call(args))
    455  
    456 def _extractall(self, path=".", members=None):
    457     """Extract all members from the archive to the current working
    458        directory and set owner, modification time and permissions on
    459        directories afterwards. `path' specifies a different directory
    460        to extract to. `members' is optional and must be a subset of the
    461        list returned by getmembers().
    462     """
    463     import copy
    464     import operator
    465     from tarfile import ExtractError
    466     directories = []
    467  
    468     if members is None:
    469         members = self
    470  
    471     for tarinfo in members:
    472         if tarinfo.isdir():
    473             # Extract directories with a safe mode.
    474             directories.append(tarinfo)
    475             tarinfo = copy.copy(tarinfo)
    476             tarinfo.mode = 448  # decimal for oct 0700
    477         self.extract(tarinfo, path)
    478  
    479     # Reverse sort directories.
    480     if sys.version_info < (2, 4):
    481         def sorter(dir1, dir2):
    482             return cmp(dir1.name, dir2.name)
    483         directories.sort(sorter)
    484         directories.reverse()
    485     else:
    486         directories.sort(key=operator.attrgetter('name'), reverse=True)
    487  
    488     # Set correct owner, mtime and filemode on directories.
    489     for tarinfo in directories:
    490         dirpath = os.path.join(path, tarinfo.name)
    491         try:
    492             self.chown(tarinfo, dirpath)
    493             self.utime(tarinfo, dirpath)
    494             self.chmod(tarinfo, dirpath)
    495         except ExtractError:
    496             e = sys.exc_info()[1]
    497             if self.errorlevel > 1:
    498                 raise
    499             else:
    500                 self._dbg(1, "tarfile: %s" % e)
    501  
    502 def _build_install_args(options):
    503     """
    504     Build the arguments to 'python setup.py install' on the distribute package
    505     """
    506     install_args = []
    507     if options.user_install:
    508         if sys.version_info < (2, 6):
    509             log.warn("--user requires Python 2.6 or later")
    510             raise SystemExit(1)
    511         install_args.append('--user')
    512     return install_args
    513  
    514 def _parse_args():
    515     """
    516     Parse the command line for options
    517     """
    518     parser = optparse.OptionParser()
    519     parser.add_option(
    520         '--user', dest='user_install', action='store_true', default=False,
    521         help='install in user site package (requires Python 2.6 or later)')
    522     parser.add_option(
    523         '--download-base', dest='download_base', metavar="URL",
    524         default=DEFAULT_URL,
    525         help='alternative URL from where to download the distribute package')
    526     options, args = parser.parse_args()
    527     # positional arguments are ignored
    528     return options
    529  
    530 def main(version=DEFAULT_VERSION):
    531     """Install or upgrade setuptools and EasyInstall"""
    532     options = _parse_args()
    533     tarball = download_setuptools(download_base=options.download_base)
    534     return _install(tarball, _build_install_args(options))
    535  
    536 if __name__ == '__main__':
    537     sys.exit(main())

     

  • 相关阅读:
    树链剖分学习笔记(未完)
    VI 配置文件(略全)
    linux之awk
    指针之基础篇
    linux之sed
    sqlplus命令手册
    Leetcode复习: 堆和栈
    leetcode 的shell部分4道题整理
    Regular Expression Matching [leetcode]
    深入浅出JAVA
  • 原文地址:https://www.cnblogs.com/canxuexiecheng/p/3683069.html
Copyright © 2020-2023  润新知