コード例 #1
0
ファイル: launchy_util.py プロジェクト: samsonwang/LaunchyQt
def initPipPackage():
    log.info('launchy_util::initPipPackage, sys.prefix: %s' % sys.prefix)

    # print ("launchy_util::initPipPackage, env.path:", os.environ.get('PATH', ''))
    # print ("launchy_util::initPipPackage, sys.path:", sys.path)

    path = os.environ.get('PATH', '')

    log.debug('launchy_util::initPipPackage, path type: %s' % type(path))
    pathsplit = path.split(';')
    log.debug('launchy_util::initPipPackage, path split1: %s' % pathsplit)
    if not sys.prefix in pathsplit:
        pathsplit.insert(0, sys.prefix)
    log.debug('launchy_util::initPipPackage, path split2: %s' % pathsplit)
    pathjoin = ';'.join(str(s) for s in pathsplit)
    log.debug('launchy_util::initPipPackage, pathjoin: %s' % pathjoin)

    os.environ['PATH'] = pathjoin

    if sys.prefix not in sys.path:
        sys.path.insert(0, sys.prefix)
    # sys.path.insert(0, ".")

    xlib = os.path.join(sys.prefix, 'Lib')

    if os.path.exists(xlib):
        log.info('launchy_util::initPipPackage, Lib path found, init site')
        if xlib not in sys.path:
            sys.path.insert(0, xlib)
        import site
        site.main()
        os.chdir(sys.prefix)
    else:
        log.info(
            'launchy_util::initPipPackage, Lib path not found, skip init site')
コード例 #2
0
def install_package(package):
    """Install a pip package to the user's site-packages directory."""
    import pip
    exitval = pip.main(['install', '--user', package])
    if exitval == 0:
        # Reload sys.path to make sure the user's site-packages are in sys.path
        import site
        site.main()
    return exitval == 0
コード例 #3
0
ファイル: utils.py プロジェクト: xylar/scream
def ensure_pip():
    ###############################################################################
    try:
        import pip
    except ImportError:
        import ensurepip

        ensurepip.bootstrap(user=True)

        # needed to "rehash" available libs
        site.main()  # pylint: disable=no-member

        import pip  # pylint: disable=import-error
コード例 #4
0
    def run(self):
        _myinstall('pytest>2.3')
        if self.distribution.install_requires:
            for ir in self.distribution.install_requires:
                _myinstall(ir)

        # reload sys.path for any new libraries installed
        import site
        site.main()
        print sys.path
        # use pytest to run tests
        pytest = __import__('pytest')
        pytest.main(['-s', 'src'])
コード例 #5
0
ファイル: debug.py プロジェクト: BMXE/music-player
def addSysPythonPath():
    import appinfo
    import os

    def addpath(p):
        try:
            p = os.path.normpath(p)
            p = os.path.abspath(p)
        except OSError:
            return
        if not os.path.exists(p):
            return
        if p not in sys.path:
            sys.path += [p]

    paths = os.environ.get("PYTHONPATH", "").split(":")
    for p in paths:
        addpath(p.strip())

    versionStr = ".".join(map(str, sys.version_info[0:2]))

    if sys.platform == "darwin":
        addpath(
            "/usr/local/Frameworks/Python.framework/Versions/%s/lib/python%s/lib-dynload/" % (versionStr, versionStr)
        )
        addpath("/System/Frameworks/Python.framework/Versions/%s/lib/python%s/lib-dynload/" % (versionStr, versionStr))

        # This will add other custom paths, e.g. for eggs.
    import site

    site.main()

    def addsitedir(d):
        try:
            d = os.path.normpath(d)
            d = os.path.abspath(d)
        except OSError:
            return
        if os.path.exists(d):
            site.addsitedir(d)

            # We still might miss some site-dirs.

    addsitedir("/usr/local/lib/python%s/site-packages" % versionStr)
    addsitedir("/usr/lib/python%s/site-packages" % versionStr)
    if sys.platform == "darwin":
        addsitedir("/Library/Python/%s/site-packages" % versionStr)

    if not appinfo.args.forkExecProc:
        print("Python paths after: %r" % sys.path)
コード例 #6
0
def ensure_pip():
    ###############################################################################
    """
    Ensures that pip is available. Notice that we cannot use the _ensure_pylib_impl
    function below, since it would cause circular dependencies. This one has to
    be done by hand.
    """
    # Use ensurepip for installing pip
    import ensurepip
    ensurepip.bootstrap(user=True)

    # needed to "rehash" available libs
    site.main()  # pylint: disable=no-member

    _ = import_module("pip")
コード例 #7
0
ファイル: ginstall.py プロジェクト: oracle/graalpython
 def wrapper(*args, **kwargs):
     _name = name if name else func.__name__
     try:
         module_name = get_module_name(_name)
         importlib.import_module(module_name)
         importlib.invalidate_caches()
     except (ImportError, ModuleNotFoundError):
         info("Installing required dependency: {} ... ", _name)
         func(*args, **kwargs)
         if try_import:
             import site
             site.main()
             importlib.invalidate_caches()
             importlib.import_module(module_name)
         info("{} installed successfully", _name)
コード例 #8
0
ファイル: site.py プロジェクト: Aletrip-dev/Cusro_Python
def add_global_site_package():
    """add the global site package"""
    import site

    # add user site package
    sys.flags = sys.original_flags  # restore original
    site.ENABLE_USER_SITE = None  # reset user site check
    # add the global site package to the path - use new prefix and delegate to site.py
    orig_prefixes = None
    try:
        orig_prefixes = site.PREFIXES
        site.PREFIXES = [sys.base_prefix, sys.base_exec_prefix]
        site.main()
    finally:
        site.PREFIXES = orig_prefixes
コード例 #9
0
ファイル: setup.py プロジェクト: stephanie-wang/streamcorpus
 def run(self):
     # ensure that pytest is installed
     _myinstall('pytest>=2.3')
     # and everything else we'd need. setuptools tests_require is dumb because it copies locally instead of installing to system, and install_requires isn't used untill install (but maybe someone wants to run the test before they install).
     for pkgspec in install_requires:
         _myinstall(pkgspec)
     print sys.path
     # reload sys.path for any new libraries installed
     import site
     site.main()
     print sys.path
     # use pytest to run tests
     pytest = __import__('pytest')
     if pytest.main(['-s', 'src']):
         sys.exit(1)
コード例 #10
0
ファイル: setup.py プロジェクト: diffeo/poly-open
    def run(self):
        if self.distribution.install_requires:
            for ir in self.distribution.install_requires:
                _myinstall(ir)
        if self.distribution.tests_require:
            for ir in self.distribution.tests_require:
                _myinstall(ir)

        # reload sys.path for any new libraries installed
        import site
        site.main()
        print sys.path
        pytest = __import__('pytest')
        if pytest.main(['-n', '3', '-vvs', 'poly_test/tests']):
            sys.exit(1)
コード例 #11
0
ファイル: setup.py プロジェクト: zzmjohn/streamcorpus
 def run(self):
     # ensure that pytest is installed
     _myinstall('pytest>=2.3')
     # and everything else we'd need. setuptools tests_require is dumb because it copies locally instead of installing to system, and install_requires isn't used untill install (but maybe someone wants to run the test before they install).
     for pkgspec in install_requires:
         _myinstall(pkgspec)
     print sys.path
     # reload sys.path for any new libraries installed
     import site
     site.main()
     print sys.path
     # use pytest to run tests
     pytest = __import__('pytest')
     if pytest.main(['-s', 'src']):
         sys.exit(1)
コード例 #12
0
ファイル: debug.py プロジェクト: LoweReception/music-player
def addSysPythonPath():
    import appinfo
    import os

    def addpath(p):
        try:
            p = os.path.normpath(p)
            p = os.path.abspath(p)
        except OSError:
            return
        if not os.path.exists(p): return
        if p not in sys.path: sys.path += [p]

    paths = os.environ.get("PYTHONPATH", "").split(":")
    for p in paths:
        addpath(p.strip())

    versionStr = ".".join(map(str, sys.version_info[0:2]))

    if sys.platform == "darwin":
        addpath(
            "/usr/local/Frameworks/Python.framework/Versions/%s/lib/python%s/lib-dynload/"
            % (versionStr, versionStr))
        addpath(
            "/System/Frameworks/Python.framework/Versions/%s/lib/python%s/lib-dynload/"
            % (versionStr, versionStr))

    # This will add other custom paths, e.g. for eggs.
    import site
    site.main()

    def addsitedir(d):
        try:
            d = os.path.normpath(d)
            d = os.path.abspath(d)
        except OSError:
            return
        if os.path.exists(d):
            site.addsitedir(d)

    # We still might miss some site-dirs.
    addsitedir("/usr/local/lib/python%s/site-packages" % versionStr)
    addsitedir("/usr/lib/python%s/site-packages" % versionStr)
    if sys.platform == "darwin":
        addsitedir("/Library/Python/%s/site-packages" % versionStr)

    if not appinfo.args.forkExecProc:
        print("Python paths after: %r" % sys.path)
コード例 #13
0
def get_venv_handler():
    log('Activating venv with executable at %s\n' % activate_this)
    import site
    sys.executable = activate_this
    old_sys_path, sys.path = sys.path, []

    site.main()

    sys.path.insert(0, '')
    for item in old_sys_path:
        if item not in sys.path:
            sys.path.append(item)

    log('Getting handler %s\n' % os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    handler = get_wsgi_handler(os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    log('Got handler: %r\n' % handler)
コード例 #14
0
ファイル: setup.py プロジェクト: diffeo/dblogger
    def run(self):
        if self.distribution.install_requires:
            for ir in self.distribution.install_requires:
                _myinstall(ir)
        if self.distribution.tests_require:
            for ir in self.distribution.tests_require:
                _myinstall(ir)

        # reload sys.path for any new libraries installed
        import site
        site.main()
        print sys.path
        # use pytest to run tests
        pytest = __import__('pytest')
        if pytest.main(['-n', '8', '-s', 'dblogger', '--runperf', '--runslow']):
            sys.exit(1)
コード例 #15
0
    def run(self):
        if self.distribution.install_requires:
            for ir in self.distribution.install_requires:
                _myinstall(ir)
        if self.distribution.tests_require:
            for ir in self.distribution.tests_require:
                _myinstall(ir)

        # reload sys.path for any new libraries installed
        import site
        site.main()
        print sys.path
        # use pytest to run tests
        pytest = __import__('pytest')
        if pytest.main(['-n', '8', '-vvs', 'streamcorpus_pipeline']):
            sys.exit(1)
コード例 #16
0
    def run(self):
        if self.distribution.install_requires:
            for ir in self.distribution.install_requires:
                _myinstall(ir)
        if self.distribution.tests_require:
            for ir in self.distribution.tests_require:
                _myinstall(ir)

        # reload sys.path for any new libraries installed
        import site
        site.main()
        print sys.path
        # use pytest to run tests
        pytest = __import__('pytest')
        if pytest.main(['-n', '8', '-vvs', 'streamcorpus_pipeline']):
            sys.exit(1)
コード例 #17
0
def get_venv_handler():
    log('Activating venv with executable at %s\n' % activate_this)
    import site
    sys.executable = activate_this
    old_sys_path, sys.path = sys.path, []

    site.main()

    sys.path.insert(0, '')
    for item in old_sys_path:
        if item not in sys.path:
            sys.path.append(item)

    log('Getting handler %s\n' % os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    handler = get_wsgi_handler(os.getenv('WSGI_ALT_VIRTUALENV_HANDLER'))
    log('Got handler: %r\n' % handler)
    return handler
コード例 #18
0
ファイル: setup.py プロジェクト: nestorsokil/pyaccumulo
    def run(self):
        cmd = ['pip', 'install']
        if self.distribution.install_requires:
            cmd.extend(self.distribution.install_requires)
        if self.distribution.tests_require:
            cmd.extend(self.distribution.tests_require)
        errno = subprocess.call(cmd)
        if errno:
            raise SystemExit(errno)

        # reload sys.path for any new libraries installed
        import site
        site.main()
        print(sys.path)
        # use pytest to run tests
        pytest = __import__('pytest')
        exitcode = pytest.main(['--cov', 'pyaccumulo', '--cov-report', 'term', '-vvs', 'tests'])
        sys.exit(exitcode)
コード例 #19
0
ファイル: setup.py プロジェクト: TITAN1287/pyaccumulo
    def run(self):
        cmd = ['pip', 'install']
        if self.distribution.install_requires:
            cmd.extend(self.distribution.install_requires)
        if self.distribution.tests_require:
            cmd.extend(self.distribution.tests_require)
        errno = subprocess.call(cmd)
        if errno:
            raise SystemExit(errno)

        # reload sys.path for any new libraries installed
        import site
        site.main()
        print sys.path
        # use pytest to run tests
        pytest = __import__('pytest')
        exitcode = pytest.main(['--cov', 'pyaccumulo', '--cov-report', 'term', '-vvs', 'tests'])
        sys.exit(exitcode)
コード例 #20
0
def pip_install_lib(pip_libname):
    ###############################################################################
    """
    Ask pip to install a version of a package which is >= min_version
    """
    # Installs will use pip, so we need to ensure it is available
    ensure_pip()

    # Note: --trusted-host may not work for ancient versions of python
    #       --upgrade makes sure we get the latest version, even if one is already installed
    stat, _, err = run_cmd(
        "{} -m pip install --upgrade {} --trusted-host files.pythonhosted.org --user"
        .format(sys.executable, pip_libname))
    expect(
        stat == 0,
        "Failed to install {}, cannot continue:\n{}".format(pip_libname, err))

    # needed to "rehash" available libs
    site.main()  # pylint: disable=no-member
コード例 #21
0
def initPipPackage():
    import sys, os
    print("pluginconf, initPipPackage, sys.prefix:", sys.prefix)
    xlib = os.path.join(sys.prefix, 'Lib')
    sys.path.insert(0, xlib)
    sys.path.insert(0, sys.prefix)
    sys.path.insert(0, ".")

    path = os.environ.get('PATH', '')
    #print ("env.path(origin):", path)
    os.environ['PATH'] = path + os.pathsep + sys.prefix + os.pathsep

    print("pluginconf, initPipPackage, sys.path:", sys.path)
    print("pluginconf, initPipPackage, env.path:", os.environ.get('PATH', ''))

    import site
    site.main()

    os.chdir(sys.prefix)
コード例 #22
0
ファイル: utils.py プロジェクト: xylar/scream
def ensure_yaml():
    ###############################################################################
    try:
        import yaml
    except ImportError:
        print("Detected missing pyyaml, will attempt to install locally")

        ensure_pip()

        # --trusted-host may not work for ancient versions of python
        stat, _, err = run_cmd(
            "{} -m pip install pyyaml --trusted-host files.pythonhosted.org --user"
            .format(sys.executable))
        expect(stat == 0,
               "Failed to install pyyaml, cannot continue:\n{}".format(err))

        # needed to "rehash" available libs
        site.main()  # pylint: disable=no-member

        import yaml  # pylint: disable=import-error
コード例 #23
0
def initPipPackage():
    import sys, os
    print("launchy_util, initPipPackage, sys.prefix:", sys.prefix)

    xlib = os.path.join(sys.prefix, 'Lib')

    if os.path.exists(xlib):
        print("launchy_util, initPipPackage, Lib path found, init site")
        sys.path.insert(0, xlib)
        sys.path.insert(0, sys.prefix)
        sys.path.insert(0, ".")

        path = os.environ.get('PATH', '')
        #print ("env.path(origin):", path)
        os.environ['PATH'] = path + os.pathsep + sys.prefix + os.pathsep

        #print("launchy_util, initPipPackage, sys.path:", sys.path)
        #print("launchy_util, initPipPackage, env.path:", os.environ.get('PATH', ''))

        import site
        site.main()
        os.chdir(sys.prefix)
    else:
        print("launchy_util, initPipPackage, Lib path not found, skip init site")
コード例 #24
0
ファイル: get_search_paths.py プロジェクト: amos402/PTVS
# 
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.

__author__ = "Microsoft Corporation <*****@*****.**>"
__version__ = "3.2"

import sys

if 'site' in sys.modules:
    raise RuntimeError('script must be run with -S')

BEFORE_SITE = list(sys.path)
import site
try:
    site.main()
except:
    import traceback
    traceback.print_exc(file=sys.stderr)
AFTER_SITE = list(sys.path)

import os
def clean(path):
    if path:
        return os.path.normcase(os.path.abspath(path).rstrip('/\\'))
    return None

BEFORE_SITE = set(clean(p) for p in BEFORE_SITE)
AFTER_SITE = set(clean(p) for p in AFTER_SITE)

for prefix in [
コード例 #25
0
#!/usr/bin/python -S
# Automatically generated on Sun Mar  1 16:17:32 2015

'''Runs a specific user program'''


import sys
sys.path[0:0] = [
  '/home/dingz/bob.spear-1.1.8/eggs/gridtk-1.2.0-py2.7.egg',
  '/home/dingz/bob.spear-1.1.8/eggs/six-1.9.0-py2.7.egg',
  '/home/dingz/bob.spear-1.1.8',
  '/home/dingz/bob.spear-1.1.8/eggs/xbob.sox-1.1.0-py2.7-linux-x86_64.egg',
  '/home/dingz/bob.spear-1.1.8/eggs/xbob.db.voxforge-0.1.0-py2.7.egg',
  '/home/dingz/bob.spear-1.1.8/eggs/xbob.db.verification.filelist-1.3.5-py2.7.egg',
  '/home/dingz/bob.spear-1.1.8/eggs/facereclib-1.2.3-py2.7.egg',
  '/home/dingz/bob.spear-1.1.8/eggs/xbob.db.verification.utils-1.0.1-py2.7.egg',
  '/home/dingz/bob.spear-1.1.8/eggs/xbob.db.atnt-1.1.2-py2.7.egg',
  ]
import site #initializes site properly
site.main() #this is required for python>=3.4
import pkg_resources #initializes virtualenvs properly

import spear.script.spkverif_jfa

if __name__ == '__main__':
    sys.exit(spear.script.spkverif_jfa.main())
コード例 #26
0
ファイル: PBS_cray_atom.PY プロジェクト: lovecandy126/openpbs
"""
PBS hook for consuming the Shasta Northbound API.

This hook services the following events:
- execjob_begin
- execjob_end
"""


import json as JSON
import os
import site
import sys
import urllib

site.main()

# to be PEP-8 compliant, the imports must be indented
if True:
    import requests
    import requests_unixsocket
    import pbs
    import pwd
    import copy

requests_unixsocket.monkeypatch()

# ============================================================================
# Utility functions
# ============================================================================
コード例 #27
0
def run():
    """Run the steps for the gcloud setup."""

    # We need to install all the required packages before importing our modules
    # Installing required packages
    install_required_packages()
    site.main()  # Load up the package

    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--no-cloudshell',
                        action='store_true',
                        help='Bypass Cloud Shell requirement')
    parser.add_argument('--service-account-key-file',
                        help=('Absolute path and filename for service account '
                              'key file'))
    parser.add_argument('--type',
                        choices=['client', 'server'],
                        help='Type of the installation, '
                        'either client or server')
    parser.add_argument('--composite-root-resources',
                        help='The resource ids to be inventoried.\n'
                        'Without this flag, the entire org '
                        'will be attempted.\n'
                        'Resources must be comma-separated and '
                        'in the form type/id,\nwhere type is '
                        'one of organizations, folders, or projects.')
    parser.add_argument('--project-id',
                        help='The project id for the forseti installaltion.')

    group = parser.add_argument_group(title='regions')
    group.add_argument('--gcs-location',
                       help='The GCS bucket location',
                       default='us-central1')
    group.add_argument('--cloudsql-region',
                       help='The Cloud SQL region',
                       default='us-central1')

    network = parser.add_argument_group(title='network')
    network.add_argument('--vpc-host-project-id',
                         help='The project id that is hosting the network '
                         'resources.')
    network.add_argument('--vpc-host-network',
                         help='The VPC name where Forseti VM will run.')
    network.add_argument('--vpc-host-subnetwork',
                         help='The subnetwork name where Forseti VM will run.')

    email_params = parser.add_argument_group(title='email')
    email_params.add_argument('--sendgrid-api-key', help='Sendgrid API key')
    email_params.add_argument('--notification-recipient-email',
                              help='Notification recipient email')
    email_params.add_argument('--skip-sendgrid-config',
                              action='store_true',
                              help='Skip Sendgrid cofiguration')
    email_params.add_argument('--gsuite-superadmin-email',
                              help='G Suite super admin email')

    args = vars(parser.parse_args())

    # Set the current date time stamp
    args['datetimestamp'] = datetime.datetime.now().strftime('%Y%m%d%H%M%S')

    # import installers and configs
    from installer.forseti_server_installer import ForsetiServerInstaller
    from installer.forseti_client_installer import ForsetiClientInstaller
    from installer.configs.client_config import ClientConfig
    from installer.configs.server_config import ServerConfig
    client_config = ClientConfig(**args)
    server_config = ServerConfig(**args)

    if not args.get('type'):
        # If the user didn't specify a type, install both server and client
        forseti_server = ForsetiServerInstaller(server_config)
        instructions = forseti_server.run_setup(final_setup=False)
        # Server and client will have the same identifier to keep them
        # consistent.
        client_config.identifier = server_config.identifier
        ForsetiClientInstaller(client_config, forseti_server).run_setup(
            setup_continuation=True, previous_instructions=instructions)
        return

    if args.get('type') == 'server':
        forseti_setup = ForsetiServerInstaller(server_config)
    else:
        forseti_setup = ForsetiClientInstaller(client_config)

    forseti_setup.run_setup()
コード例 #28
0
ファイル: nodes.py プロジェクト: xxoolm/Ryven
 def update_event(self, inp=-1):
     self.set_output_val(0, site.main())
コード例 #29
0
ファイル: pyexe.py プロジェクト: shshzi/pyexe
def main():  # noqa
    import ctypes
    import os
    import six
    import sys
    import warnings

    AllModules = False

    if len(sys.argv) == 1 and not hasattr(sys, 'frozen'):
        AllModules = True
    if not AllModules and sys.argv[:2][-1] != '--all':
        pass
    else:
        # IMPORT ALL MODULES
        import modules_pyexe_list  # noqa, this is the output of modules_pyexe
        print(dir(modules_pyexe_list))  # for installers to include submodules
        # END IMPORT ALL MODULES
        # Import modules which failed to be included in the auto-generated list.
        import setuptools._vendor.pyparsing  # noqa

    def alternate_raw_input(prompt=None):
        """
        Write the prompt to stderr, then call raw_input without a prompt.  This
        is to try to mimic better what the python executable does.

        Enter: prompt: prompt to print to stderr.
        """
        if prompt and len(prompt):
            sys.stderr.write(prompt)
            sys.stderr.flush()
        return six.moves.input('')

    def get_env_flag(currentValue, key):
        """
        Check if the environment has a key.  Parse this as a positive integer,
        if possible, otherwise treat it like 1.  Return the greater of the
        current value and the parsed value.
        """
        if not os.environ.get(key):
            return currentValue
        try:
            value = int(os.environ.get(key))
            if value < 0:
                value = 1
        except ValueError:
            value = 1
        return max(currentValue, value)

    def print_version(details=1):
        """
        Print the current version.

        Enter: details: 0 if part of help, 1 for basic verison, 2 for more
                    details.
        """
        from py_version import Version, Description

        print('%s, Version %s' % (Description, Version))
        if details > 1:
            print('Python %s' % (sys.version))
            # pywin32
            import win32api
            fileinfo = win32api.GetFileVersionInfo(win32api.__file__, '\\')
            print('pywin32: %s' % str(fileinfo['FileVersionLS'] >> 16))
            # Others
            import importlib
            for module_name in ('pip', 'psutil', 'setuptools', 'six'):
                module = importlib.import_module(module_name)
                print('%s: %s' % (module_name, module.__version__))

    def run_file(runFile, runFileArgv, skipFirstLine, globenv):
        """
        Exec a file with a limited set of globals.  We can't use runpy.run_path
        for (a) skipped first line, (b) Python 2.7 and zipapps (pyz files).
        Rather than use run_path in the limited cases where it can be used, we
        use one code path for executing files in general.

        Enter: runFile: path of the file to exec.
               runFileArgv: arguments to set sys.argv to.
               SkipFileLine: True to skip the first line of the file.
               globenv: global environment to use.
        """
        import codecs
        import re
        import zipfile
        sys.argv[:] = runFileArgv
        if zipfile.is_zipfile(os.path.abspath(runFile)):
            sys.path[0:0] = [runFile]
            with zipfile.ZipFile(runFile) as zptr:
                src = zptr.open('__main__.py').read()
        else:
            if not Isolated:
                sys.path[0:0] = [os.path.split(os.path.abspath(runFile))[0]]
            with open(runFile, 'rb') as fptr:
                src = fptr.read()
                # This is similar to what universal newline support does
                useenc = 'utf-8' if sys.version_info >= (3, ) else 'latin-1'
                if src.startswith(codecs.BOM_UTF8):
                    useenc = 'utf-8'
                    src = src[len(codecs.BOM_UTF8):]
                src = src.replace(b'\r\n', b'\n').replace(b'\r', b'\n')
                if skipFirstLine:
                    src = src.split(b'\n', 1)[1] if b'\n' in src else b''
                # first two lines may contain encoding:
                firsttwo = src.split(b'\n', 2)
                coding_re = re.compile(
                    r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)')
                try:
                    match = coding_re.match(firsttwo[0].decode('utf8'))
                except Exception:
                    match = None
                if match:
                    useenc = match.group(1)
                    src = b'\n'.join(firsttwo[1:])
                else:
                    try:
                        match = coding_re.match(firsttwo[1].decode('utf8'))
                    except Exception:
                        match = None
                    if match:
                        useenc = match.group(1)
                        src = b'\n'.join(firsttwo[:1] + firsttwo[2:])
                src = src.decode(useenc)
        # If we use anything other than the actual globals() dictionary,
        # multiprocessing doesn't work.  Therefore, mutate globals() and
        # merge back in when done.
        globs = globals()
        originalGlobals = globs.copy()
        globs.clear()
        globs.update(globenv)
        globs['__name__'] = '__main__'
        globs['__file__'] = runFile
        six.exec_(src, globs)
        # globs.clear()
        globs.update(originalGlobals)

    def skip_once(cls, method):
        """
        The first time a mthod of a class is called, skip doing the action.

        Enter: cls: the class instance with the method.
               method: the name of the method (a string).
        """
        orig = getattr(cls, method, None)

        def skip(*args, **kwargs):
            setattr(cls, method, orig)

        setattr(cls, method, skip)

    if hasattr(sys, 'frozen'):
        delattr(sys, 'frozen')
    Help = False
    Interactive = None
    InteractiveArgv = None
    Isolated = False
    NoSiteFlag = False
    Optimize = 0
    PrintVersion = 0
    QuietFlag = False
    RunCommand = None
    RunFile = None
    RunModule = None
    SkipFirstLine = False
    StartupFile = None
    TabcheckFlag = 0
    Unbuffered = False
    UseEnvironment = True
    VerboseFlag = 0
    Warning3k = 0
    WarningBytes = 0
    WarningDivision = None
    WarningOptions = []
    skip = 0
    sys.dont_write_bytecode = False
    for i in six.moves.range(1, len(sys.argv)):  # noqa
        if skip:
            skip -= 1
            continue
        arg = sys.argv[i]
        if arg.startswith('-') and len(arg) > 1 and arg[1:2] != '-':
            for let in arg[1:]:
                if let == 'b':
                    WarningBytes += 1
                elif let == 'B':
                    sys.dont_write_bytecode = True
                elif let == 'c':
                    RunCommand = sys.argv[i + 1 + skip]
                    RunCommandArgv = ['-c'] + sys.argv[i + 2 + skip:]
                    skip = len(sys.argv)
                elif let == 'd':
                    # We don't have to do anything for this flag, since we
                    # never bundle with a debug build of Python
                    pass
                elif let == 'E':
                    UseEnvironment = False
                elif let == 'h':
                    Help = True
                elif let == 'i':
                    Interactive = True
                elif let == 'I' and sys.version_info >= (3, ):
                    UseEnvironment = False
                    Isolated = True
                elif let == 'm' and i + 1 < len(sys.argv):
                    RunModule = sys.argv[i + 1 + skip]
                    RunModuleArgv = sys.argv[i + 1 + skip:]
                    skip = len(sys.argv)
                elif let == 'O':
                    Optimize += 1
                elif let == 'q' and sys.version_info >= (3, ):
                    QuietFlag = True
                elif let == 'Q' and sys.version_info < (3, ):
                    if arg.startswith('-' + let) and len(arg) > 2:
                        WarningDivision = arg[2:]
                    else:
                        WarningDivision = sys.argv[i + 1 + skip]
                        skip += 1
                    if WarningDivision not in ('old', 'warn', 'warnall',
                                               'new'):
                        sys.stderr.write(
                            """-Q option should be `-Qold', `-Qwarn', `-Qwarnall', or `-Qnew' only
usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `%s -h' for more information.
    """ % (sys.argv[0], sys.argv[0]))
                        sys.exit(2)
                    if arg.startswith('-' + let) and len(arg) > 2:
                        break
                elif let == 'R':
                    # We can't change the hash seed after start, so ignore it.
                    pass
                elif let == 's':
                    # We don't have to do anything for this flag, since we
                    # never have a local user site-packages directory in
                    # stand-alone mode
                    pass
                elif let == 'S':
                    NoSiteFlag = True
                elif let == 't' and sys.version_info < (3, ):
                    TabcheckFlag += 1
                elif let == 'u':
                    Unbuffered = True
                elif let == 'v':
                    VerboseFlag += 1
                elif let == 'V':
                    PrintVersion += 1
                elif let == 'W':
                    if arg.startswith('-' + let) and len(arg) > 2:
                        WarningOptions.append(arg[2:])
                        break
                    else:
                        WarningOptions.append(sys.argv[i + 1 + skip])
                        skip += 1
                elif let == 'x':
                    SkipFirstLine = True
                elif let == 'X':
                    # We don't have do anything for this flag, as the basic
                    # implementation doesn't have such options.
                    if arg.startswith('-' + let) and len(arg) > 2:
                        break
                    else:
                        skip += 1
                elif let == '3' and sys.version_info < (3, ):
                    Warning3k += 1
                    TabcheckFlag = max(TabcheckFlag, 1)
                else:
                    Help = True
        elif ((arg == '--check-hash-based-pycs'
               or arg.startswith('--check-hash-based-pycs='))
              and sys.version_info >= (3, 6)):
            # There is no exposure to this option in Python's DLL, so can't do
            # it
            if '=' not in arg:
                skip += 1
        elif arg == '--all':
            pass
        elif arg == '--help' or arg == '/?':
            Help = True
        elif arg == '--version':
            PrintVersion += 1
        elif arg == '-':
            Interactive = 'check'
            InteractiveArgv = ['-'] + sys.argv[i + 1 + skip:]
            skip = len(sys.argv)
        elif arg.startswith('-'):
            Help = True
        elif not RunFile:
            RunFile = sys.argv[i + skip]
            RunFileArgv = sys.argv[i + skip:]
            skip = len(sys.argv)
    if Help:
        print_version(0)
        print('usage: %s [option] ... [-c cmd | -m mod | file | -] [arg] ...' %
              sys.argv[0])
        print(
            """Options and arguments (and corresponding environment variables):"""
        )
        if sys.version_info >= (3, ):
            print(
                """-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)""")
        print(
            """-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help, /?)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x""")
        if sys.version_info >= (3, ):
            print(
                """-I     : isolate Python from the user's environment (implies -E and -s)"""
            )
        print(
            """-m mod : run library module as a script (terminates option list)
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO    : remove doc-strings in addition to the -O optimizations""")
        if sys.version_info >= (3, ):
            print(
                """-q     : don't print version and copyright messages on interactive startup"""
            )
        if sys.version_info < (3, ):
            print(
                """-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew"""
            )
        print(
            """-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization""")
        if sys.version_info < (3, ):
            print(
                """-t     : issue warnings about inconsistent tab usage (-tt: issue errors)"""
            )
        print(
            """-u     : unbuffered binary stdout and stderr, stdin always buffered;
         also PYTHONUNBUFFERED=x
         see man page for details on internal buffering relating to '-u'
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version).  Use twice
         for more complete information.
-W arg : warning control; arg is action:message:category:module:lineno
         also PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option""")
        if sys.version_info < (3, ):
            print(
                """-3     : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix"""
            )  # noqa
        print("""file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Stand-alone specific options:
--all  : imports all bundled modules.

Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ';'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONCASEOK : ignore case in 'import' statements (Windows).""")
        sys.exit(0)
    if PrintVersion:
        print_version(PrintVersion)
        sys.exit(0)
    # Explicitly add the path of the current executable to the system paths and
    # its subpath of Lib\site-packages.  Installed Python always includes these
    # paths, but PyInstaller changes them to the expanded paths.
    sys.path[0:0] = [
        os.path.abspath(os.path.dirname(sys.executable)),
        os.path.abspath(
            os.path.join(os.path.dirname(sys.executable), 'Lib',
                         'site-packages'))
    ]
    if UseEnvironment:
        if os.environ.get('PYTHONDONTWRITEBYTECODE'):
            sys.dont_write_bytecode = True
        if Interactive is not True and os.environ.get('PYTHONINSPECT'):
            Interactive = 'check'
        Optimize = get_env_flag(Optimize, 'PYTHONOPTIMIZE')
        if os.environ.get('PYTHONPATH'):
            sys.path[0:0] = os.environ.get('PYTHONPATH').split(os.pathsep)
        StartupFile = os.environ.get('PYTHONSTARTUP')
        if Unbuffered is False and os.environ.get('PYTHONUNBUFFERED'):
            Unbuffered = True
        VerboseFlag = get_env_flag(VerboseFlag, 'PYTHONVERBOSE')
        if os.environ.get('PYTHONWARNINGS'):
            WarningOptions.extend(os.environ.get('PYTHONWARNINGS').split(','))
    if Isolated:
        # We have to suppress some environment effects
        os.environ.pop('PYTHONCASEOK', None)
        for key in list(sys.modules):  # for Python 3.x
            if hasattr(sys.modules[key], '_relax_case'):
                sys.modules[key]._relax_case = lambda: False
    if VerboseFlag:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_VerboseFlag').value = VerboseFlag
    if TabcheckFlag:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_TabcheckFlag').value = TabcheckFlag
    if Warning3k:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_Py3kWarningFlag').value = Warning3k
    if Optimize:
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_OptimizeFlag').value = Optimize
    if WarningBytes:
        for idx, f in enumerate(warnings.filters):
            if f[2] == BytesWarning:
                warnings.filters[idx] = tuple(
                    ['default' if WarningBytes == 1 else 'error'] +
                    list(f)[1:])
        if not any([f for f in warnings.filters if f[2] == BytesWarning]):
            warnings.filterwarnings(
                'default' if WarningBytes == 1 else 'error',
                category=BytesWarning)
        ctypes.c_int.in_dll(ctypes.pythonapi,
                            'Py_BytesWarningFlag').value = WarningBytes
    if WarningDivision == 'new':
        ctypes.c_int.in_dll(ctypes.pythonapi, '_Py_QnewFlag').value = 1
    elif WarningDivision in ('warn', 'warnall') or Warning3k:
        ctypes.c_int.in_dll(
            ctypes.pythonapi,
            'Py_DivisionWarningFlag').value = (2 if WarningDivision
                                               == 'warnall' else 1)
        warnings.filterwarnings('default',
                                category=DeprecationWarning,
                                message='classic [a-z]+ division')
    if Warning3k:
        warnings.filterwarnings('default', category=DeprecationWarning)
    sys.warnoptions[0:0] = WarningOptions
    warnings._processoptions(WarningOptions)
    bufsize = 1 if sys.version_info >= (3, ) else 0
    if Unbuffered:
        sys.stdin = os.fdopen(sys.stdin.fileno(), 'r', bufsize)
        sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', bufsize)
        sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', bufsize)
    if not NoSiteFlag:
        import site
        site.main()
    # Generate the globals/locals environment
    globenv = {}
    for key in list(globals().keys()):
        if key.startswith(
                '_') and not key in ['_frozen_name', '_setup_ctypes']:
            globenv[key] = globals()[key]
    if RunFile:
        run_file(RunFile, RunFileArgv, SkipFirstLine, globenv)
    elif RunModule:
        import runpy
        sys.argv[:] = RunModuleArgv
        runpy.run_module(RunModule, run_name='__main__')
    elif RunCommand is not None:
        if not Isolated:
            sys.path[0:0] = ['']
        sys.argv[:] = RunCommandArgv
        six.exec_(RunCommand, globenv)
    elif Interactive is None:
        Interactive = 'check'
    if Interactive:
        if not Isolated:
            sys.path[0:0] = ['']
        if InteractiveArgv:
            sys.argv[:] = InteractiveArgv
        if Interactive is True or sys.stdin.isatty():
            if not RunFile and not RunModule and not RunCommand and StartupFile:
                import runpy
                runpy.run_path(StartupFile, run_name='__main__')
            import code
            cons = code.InteractiveConsole(locals=globenv)
            if not sys.stdout.isatty():
                cons.raw_input = alternate_raw_input
                if not Unbuffered:
                    sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', bufsize)
                    sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', bufsize)
            banner = 'Python %s' % sys.version
            if not NoSiteFlag:
                banner += '\nType "help", "copyright", "credits" or "license" for more information.'
            if RunModule or RunCommand or QuietFlag:
                banner = ''
                if sys.version_info < (3, ):
                    skip_once(cons, 'write')
            kwargs = {}
            if sys.version_info >= (3, 6):
                kwargs['exitmsg'] = ''
            cons.interact(banner=banner, **kwargs)
        else:
            src = sys.stdin.read()
            # This doesn't work the way I expect for some reason
            #  interp = code.InteractiveInterpreter(locals=globenv)
            #  interp.runsource(src, '<stdin>')
            # But an exec works fine
            globenv['__file__'] = '<stdin>'
            six.exec_(src, globenv)
コード例 #30
0
#  See LICENSE.txt for details.
#
#  This software is distributed WITHOUT ANY WARRANTY; without even
#  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#  PURPOSE.  See the above copyright notice for more information.
#
# =============================================================================

""" render_mesh.py:

Render a 2-dmensional mesh using matplotlib.

"""
# use the 'sites' module to set up our path so we can find matplotlib
import site  # nopep8
site.main()  # nopep8

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import matplotlib

import smtk.operation
import smtk.mesh
import smtk.io
import smtk.attribute
import smtk
from . import render_mesh_xml


class RenderMesh(smtk.operation.Operation):
コード例 #31
0
# python3 -m site --user-site
"""
--user-base
Print the path to the user base directory.

--user-site
Print the path to the user site-packages directory.
"""
import site

print(site.PREFIXES)
print(site.ENABLE_USER_SITE)
print(site.USER_SITE)
print(site.USER_BASE)
print(site.main())
print(site.getsitepackages())
print(site.getuserbase())
print(site.getusersitepackages())
# print(site.addsitedir(""))
コード例 #32
0
def install_package(package):
    import pip, site
    exitval = pip.main(['install', '--user',
                        package])  # install package to user's site-packages
    site.main()  # Reload sys.path to include the user's site-packages
    return exitval == 0