sys.version.split

Here are the examples of the python api sys.version.split taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

82 Examples 7

Page 1 Selected Page 2

Example 1

Project: brython Source File: test_wsgiref.py
Function: check_hello
    def check_hello(self, out, has_length=True):
        pyver = (python_implementation() + "/" +
                sys.version.split()[0])
        self.assertEqual(out,
            ("HTTP/1.0 200 OK\r\n"
            "Server: WSGIServer/0.2 " + pyver +"\r\n"
            "Content-Type: text/plain\r\n"
            "Date: Mon, 05 Jun 2006 18:49:54 GMT\r\n" +
            (has_length and  "Content-Length: 13\r\n" or "") +
            "\r\n"
            "Hello, world!").encode("iso-8859-1")
        )

Example 2

Project: DragonPy Source File: humanize.py
Function: get_python_info
def get_python_info():
    implementation = platform.python_implementation()
    if implementation == "CPython":
        return "%s v%s [%s]" % (
            implementation,
            platform.python_version(),
            platform.python_compiler(),
        )
        # e.g.: CPython v2.7.6 [GCC 4.8.2]
    elif implementation == "PyPy":
        ver_info = sys.version.split("(", 1)[0]
        ver_info += sys.version.split("\n")[-1]
        return "Python %s" % ver_info
        # e.g.: Python 2.7.6 [PyPy 2.3.1 with GCC 4.8.2]
    else:
        return "%s %s" % (
            sys.executable,
            sys.version.replace("\n", " ")
        )

Example 3

Project: py-generic-project Source File: test_cli.py
Function: test_cli_version
@cli
@integration
def test_cli_version(cmd):
    result = cmd('--version')
    stdout = result.stdout.decode('ascii')
    reported_version = stdout.split()[1]
    py_version = sys.version.split()[0]

    assert version in stdout, "Version string contains version"
    assert reported_version[:len(version)] == version, "Version is 2nd field"
    assert py_version in stdout, "Python version is reported"

Example 4

Project: TrustRouter Source File: test_wsgiref.py
Function: check_hello
    def check_hello(self, out, has_length=True):
        self.assertEqual(out,
            ("HTTP/1.0 200 OK\r\n"
            "Server: WSGIServer/0.2 Python/"+sys.version.split()[0]+"\r\n"
            "Content-Type: text/plain\r\n"
            "Date: Mon, 05 Jun 2006 18:49:54 GMT\r\n" +
            (has_length and  "Content-Length: 13\r\n" or "") +
            "\r\n"
            "Hello, world!").encode("iso-8859-1")
        )

Example 5

Project: qiime2 Source File: provenance.py
    def make_env_section(self):
        env = collections.OrderedDict()
        env['platform'] = pkg_resources.get_build_platform()
        # There is a trailing whitespace in sys.version, strip so that YAML can
        # use literal formatting.
        env['python'] = LiteralString('\n'.join(line.strip() for line in
                                      sys.version.split('\n')))
        env['framework'] = qiime.__version__
        env['plugins'] = self.plugins
        env['python-packages'] = self.capture_env()

        return env

Example 6

Project: cgstudiomap Source File: ImageCms.py
Function: versions
def versions():
    """
    (pyCMS) Fetches versions.
    """

    import sys
    return (
        VERSION, core.littlecms_version,
        sys.version.split()[0], Image.VERSION
    )

Example 7

Project: pyvision Source File: __init__.py
Function: test_python_version
    def test_python_version(self):
        major,minor,sub = sys.version.split(' ')[0].split('.')[:3]
        rmajor,rminor,rsub = 2,3,0 # 2008/03/20
        major,minor,sub = int(major),int(minor),int(sub)
        print >> sys.stderr, "%d.%d.%d >= %d.%d.%d "%(major,minor,sub,rmajor,rminor,rsub),
        sys.stderr.flush()
        self.assert_(major > rmajor 
                     or major == rmajor and minor >= rminor 
                     or major == rmajor and minor == rminor and sub >= sub)

Example 8

Project: lux Source File: info.py
def _packages():
    yield 'python', ' '.join(sys.version.split('\n'))
    for p in pip.get_installed_distributions():
        try:
            yield p.key, p.version
        except Exception:
            pass

Example 9

Project: gauged Source File: bridge.py
Function: init
    def __init__(self, name, prefix):
        self.prefix = prefix
        path = os.path.dirname(os.path.realpath(os.path.join(__file__, '..')))
        version = sys.version.split(' ')[0][0:3]
        shared_lib = os.path.join(path, 'build', 'lib*-' + version,
                                  name + '*.*')
        lib = glob.glob(shared_lib)
        if not lib:  # pragma: no cover
            lib = glob.glob(os.path.join(path, name + '*.*'))
        try:
            self.library = cdll.LoadLibrary(lib[0])
        except OSError as err:
            raise OSError('Failed to load the C extension: ' + str(err))

Example 10

Project: pympler Source File: run.py
def print2(text):
    '''Print a headline text.
    '''
    if _Verbose > 0:
        print ('')
        if text:
            b =  struct.calcsize('P') << 3
            p =  sys.version.split()[0]
            t = '%s (%d-bit Python %s)' % (text, b, p)
            print (t)
            print ('=' * len(t))

Example 11

Project: jmx4py Source File: __main__.py
Function: cli
@click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(
    message='%(prog)s %(version)s [Python {}]'.format(' '.join(sys.version.split())),
)
@click.option('-q', '--quiet', is_flag=True, default=False, help='Be quiet (show only errors).')
@click.option('-v', '--verbose', is_flag=True, default=False, help='Create extra verbose output.')
@click.pass_context
def cli(ctx, version=False, quiet=False, verbose=False):  # pylint: disable=unused-argument
    """'jmx4py' command line tool."""
    appdir = click.get_app_dir(__app_name__)  # noqa

Example 12

Project: quicktill Source File: managetill.py
@user.permission_required('version','See version information')
def versioninfo():
    """
    Display the till version information.

    """
    log.info("Version popup")
    ui.infopopup(["Quick till software %s"%version,
                  "(C) Copyright 2004-2016 Stephen Early",
                  "Configuration: %s"%tillconfig.configversion,
                  "Operating system: %s %s %s"%(os.uname()[0],
                                                os.uname()[2],
                                                os.uname()[3]),
                  "Python version: %s %s"%tuple(sys.version.split('\n')),
                  td.db_version()],
                 title="Software Version Information",
                 colour=ui.colour_info,dismiss=keyboard.K_CASH)

Example 13

Project: mollie-api-python Source File: Client.py
Function: init
    def __init__(self):
        from . import Resource

        self.api_endpoint = self.API_ENDPOINT
        self.api_version = self.API_VERSION
        self.api_key = ''
        self.payments = Resource.Payments(self)
        self.payment_refunds = Resource.Refunds(self)
        self.issuers = Resource.Issuers(self)
        self.methods = Resource.Methods(self)
        self.version_strings = []
        self.addVersionString('Mollie/' + self.CLIENT_VERSION)
        self.addVersionString('Python/' + sys.version.split(' ')[0])
        self.addVersionString('OpenSSL/' + ssl.OPENSSL_VERSION.split(' ')[1])

Example 14

Project: reprozip Source File: graph.py
def disabled_bug13676(args):
    stderr.write("Error: your version of Python, %s, is not supported\n"
                 "Versions before 2.7.3 are affected by bug 13676 and will "
                 "not be able to read\nthe trace "
                 "database\n" % sys.version.split(' ', 1)[0])
    sys.exit(1)

Example 15

Project: ensembler Source File: initproject.py
    def _gen_init_metadata(self):
        datestamp = ensembler.core.get_utcnow_formatted()
        metadata_dict = {
            'datestamp': datestamp,
            'init_path': os.path.abspath(self.project_toplevel_dir),
            'python_version': sys.version.split('|')[0].strip(),
            'python_full_version': ensembler.core.literal_str(sys.version),
            'ensembler_version': ensembler.version.short_version,
            'ensembler_commit': ensembler.version.git_revision
        }
        return metadata_dict

Example 16

Project: bokeh Source File: info.py
    def invoke(self, args):
        if args.static:
            print(settings.bokehjsdir())
        else:
            try:
                import IPython
                ipy_version = IPython.__version__
            except ImportError:
                ipy_version = "Not installed"
            print("Python version      :  %s" % sys.version.split('\n')[0])
            print("IPython version     :  %s" % ipy_version)
            print("Bokeh version       :  %s" % __version__)
            print("BokehJS static path :  %s" % settings.bokehjsdir())

Example 17

Project: pymo Source File: test_wsgiref.py
Function: check_hello
    def check_hello(self, out, has_length=True):
        self.assertEqual(out,
            "HTTP/1.0 200 OK\r\n"
            "Server: WSGIServer/0.1 Python/"+sys.version.split()[0]+"\r\n"
            "Content-Type: text/plain\r\n"
            "Date: Mon, 05 Jun 2006 18:49:54 GMT\r\n" +
            (has_length and  "Content-Length: 13\r\n" or "") +
            "\r\n"
            "Hello, world!"
        )

Example 18

Project: ganga Source File: BOOT.py
def loadPlugins(c):

    import os,sys
    from Ganga.Utility.logging import getLogger
    logger = getLogger()
    logger.info('You are now using Python %s',sys.version.split()[0])

    import GangaPlotter.Plotter
    from Plotter.GangaPlotter import GangaPlotter
    #GangaPlotter.Plotter.plotter = GangaPlotter()
    plotter = GangaPlotter()

    from Ganga.Runtime.GPIexport import exportToGPI

    #exportToGPI('plotter',GangaPlotter.Plotter.plotter,'Objects','graphics plotter')
    exportToGPI('plotter',plotter,'Objects','graphics plotter')

Example 19

Project: wpbiff Source File: cli.py
def supported_python_version():
    """
    Verifies Python version
    """
    python_version = sys.version.split()[0]
    if python_version >= "3" or python_version < "2.6":
        return False
    else:
        return True

Example 20

Project: ensembler Source File: initproject.py
def gen_gather_templates_metadata(nselected_templates, additional_metadata=None):
    if additional_metadata is None:
        additional_metadata = {}
    datestamp = ensembler.core.get_utcnow_formatted()
    metadata = {
        'datestamp': datestamp,
        'ntemplates': str(nselected_templates),
        'python_version': sys.version.split('|')[0].strip(),
        'python_full_version': ensembler.core.literal_str(sys.version),
        'ensembler_version': ensembler.version.short_version,
        'ensembler_commit': ensembler.version.git_revision
    }
    metadata.update(additional_metadata)
    return metadata

Example 21

Project: ensembler Source File: initproject.py
    def _gen_gather_targets_metadata(self, ntargets, additional_metadata=None):
        if additional_metadata is None:
            additional_metadata = {}
        datestamp = ensembler.core.get_utcnow_formatted()
        metadata = {
            'datestamp': datestamp,
            'ntargets': '%d' % ntargets,
            'python_version': sys.version.split('|')[0].strip(),
            'python_full_version': ensembler.core.literal_str(sys.version),
            'ensembler_version': ensembler.version.short_version,
            'ensembler_commit': ensembler.version.git_revision,
        }
        metadata.update(additional_metadata)
        return metadata

Example 22

Project: RIDE Source File: version.py
Function: get_full_version
def get_full_version(program=None, naked=False):
    version = '%s %s (%s %s on %s)' % (program or '',
                                       get_version(naked),
                                       get_interpreter(),
                                       sys.version.split()[0],
                                       sys.platform)
    return version.strip()

Example 23

Project: muddery Source File: muddery_launcher.py
def show_version_info(about=False):
    """
    Display version info
    """
    import os, sys
    import twisted
    import django

    return VERSION_INFO.format(version=MUDDERY_VERSION,
                               about=ABOUT_INFO if about else "",
                               os=os.name, python=sys.version.split()[0],
                               twisted=twisted.version.short(),
                               django=django.get_version(),
                               evennia=evennia_launcher.evennia_version(),)

Example 24

Project: TrustRouter Source File: test_wsgiref.py
    def test_bytes_validation(self):
        def app(e, s):
            s("200 OK", [
                ("Content-Type", "text/plain; charset=utf-8"),
                ("Date", "Wed, 24 Dec 2008 13:29:32 GMT"),
                ])
            return [b"data"]
        out, err = run_amock(validator(app))
        self.assertTrue(err.endswith('"GET / HTTP/1.0" 200 4\n'))
        ver = sys.version.split()[0].encode('ascii')
        self.assertEqual(
                b"HTTP/1.0 200 OK\r\n"
                b"Server: WSGIServer/0.2 Python/" + ver + b"\r\n"
                b"Content-Type: text/plain; charset=utf-8\r\n"
                b"Date: Wed, 24 Dec 2008 13:29:32 GMT\r\n"
                b"\r\n"
                b"data",
                out)

Example 25

Project: ppft Source File: pp.py
    def __init__(self, ncpus="autodetect", ppservers=(), secret=None,
            restart=False, proto=2, socket_timeout=3600):
        """Creates Server instance

           ncpus - the number of worker processes to start on the local
                   computer, if parameter is omitted it will be set to
                   the number of processors in the system
           ppservers - list of active parallel python execution servers
                   to connect with
           secret - passphrase for network connections, if omitted a default
                   passphrase will be used. It's highly recommended to use a
                   custom passphrase for all network connections.
           restart - whether to restart worker process after each task completion
           proto - protocol number for pickle module
           socket_timeout - socket timeout in seconds which is also the maximum 
                   time a remote job could be executed. Increase this value
                   if you have long running jobs or decrease if connectivity
                   to remote ppservers is often lost.

           With ncpus = 1 all tasks are executed consequently
           For the best performance either use the default "autodetect" value
           or set ncpus to the total number of processors in the system
        """

        if not isinstance(ppservers, tuple):
            raise TypeError("ppservers argument must be a tuple")

        self.logger = logging.getLogger('pp')
        self.logger.info("Creating server instance (pp-" + version+")")
        self.logger.info("Running on Python %s %s", sys.version.split(" ")[0],
                sys.platform)
        self.__tid = 0
        self.__active_tasks = 0
        self.__active_tasks_lock = threading.Lock()
        self.__queue = []
        self.__queue_lock = threading.Lock()
        self.__workers = []
        self.__rworkers = []
        self.__rworkers_reserved = []
        self.__sourcesHM = {}
        self.__sfuncHM = {}
        self.__waittasks = []
        self.__waittasks_lock = threading.Lock()
        self._exiting = False
        self.__accurate_stats = True
        self.autopp_list = {}
        self.__active_rworkers_list_lock = threading.Lock()
        self.__restart_on_free = restart
        self.__pickle_proto = proto
        self.__connect_locks = {}

        # add local directory and sys.path to PYTHONPATH
        pythondirs = [os.getcwd()] + sys.path

        if "PYTHONPATH" in os.environ and os.environ["PYTHONPATH"]:
            pythondirs += os.environ["PYTHONPATH"].split(os.pathsep)
        os.environ["PYTHONPATH"] = os.pathsep.join(set(pythondirs))

        atexit.register(self.destroy)
        self.__stats = {"local": _Statistics(0)}
        self.set_ncpus(ncpus)

        self.ppservers = []
        self.auto_ppservers = []
        self.socket_timeout = socket_timeout

        for ppserver in ppservers:
            ppserver = ppserver.split(":")
            host = ppserver[0]
            if len(ppserver)>1:
                port = int(ppserver[1])
            else:
                port = ppc.randomport()
            if host.find("*") == -1:
                self.ppservers.append((host, port))
            else:
                if host == "*":
                    host = "*.*.*.*"
                interface = host.replace("*", "0")
                broadcast = host.replace("*", "255")
                self.auto_ppservers.append(((interface, port),
                        (broadcast, port)))
        self.__stats_lock = threading.Lock()
        if secret is not None:
            if not isinstance(secret, str):
                raise TypeError("secret must be of a string type")
            self.secret = str(secret)
        elif hasattr(user, "pp_secret"):
            secret = getattr(user, "pp_secret")
            if not isinstance(secret, str):
                raise TypeError("secret must be of a string type")
            self.secret = str(secret)
        else:
            self.secret = Server.default_secret
        self.__connect()
        self.__creation_time = time.time()
        self.logger.info("pp local server started with %d workers"
                % (self.__ncpus, ))

Example 26

Project: update_checker Source File: update_checker.py
Function: check
    @cache_results
    def check(self, package_name, package_version, **extra_data):
        """Return a UpdateResult object if there is a newer version."""
        data = extra_data
        data['package_name'] = package_name
        data['package_version'] = package_version
        data['python_version'] = sys.version.split()[0]
        data['platform'] = platform.platform(True)

        try:
            headers = {'connection': 'close',
                       'content-type': 'application/json'}
            response = requests.put(self.url, json.dumps(data), timeout=1,
                                    headers=headers)
            data = response.json()
        except (requests.exceptions.RequestException, ValueError):
            return None

        if not data or not data.get('success') \
                or (parse_version(package_version) >=
                    parse_version(data['data']['version'])):
            return None

        return UpdateResult(package_name, running=package_version,
                            available=data['data']['version'],
                            release_date=data['data']['upload_time'])

Example 27

Project: MongoApp Source File: ImageCms.py
def versions():
    import sys
    return (
        VERSION, core.littlecms_version, sys.version.split()[0], Image.VERSION
        )

Example 28

Project: ppft Source File: pp.py
    def __init__(self, ncpus="autodetect", ppservers=(), secret=None,
            restart=False, proto=2, socket_timeout=3600):
        """Creates Server instance

           ncpus - the number of worker processes to start on the local
                   computer, if parameter is omitted it will be set to
                   the number of processors in the system
           ppservers - list of active parallel python execution servers
                   to connect with
           secret - passphrase for network connections, if omitted a default
                   passphrase will be used. It's highly recommended to use a
                   custom passphrase for all network connections.
           restart - whether to restart worker process after each task completion
           proto - protocol number for pickle module
           socket_timeout - socket timeout in seconds which is also the maximum 
                   time a remote job could be executed. Increase this value
                   if you have long running jobs or decrease if connectivity
                   to remote ppservers is often lost.

           With ncpus = 1 all tasks are executed consequently
           For the best performance either use the default "autodetect" value
           or set ncpus to the total number of processors in the system
        """

        if not isinstance(ppservers, tuple):
            raise TypeError("ppservers argument must be a tuple")

        self.logger = logging.getLogger('pp')
        self.logger.info("Creating server instance (pp-" + version+")")
        self.logger.info("Running on Python %s %s", sys.version.split(" ")[0],
                sys.platform)
        self.__tid = 0
        self.__active_tasks = 0
        self.__active_tasks_lock = threading.Lock()
        self.__queue = []
        self.__queue_lock = threading.Lock()
        self.__workers = []
        self.__rworkers = []
        self.__rworkers_reserved = []
        self.__sourcesHM = {}
        self.__sfuncHM = {}
        self.__waittasks = []
        self.__waittasks_lock = threading.Lock()
        self._exiting = False
        self.__accurate_stats = True
        self.autopp_list = {}
        self.__active_rworkers_list_lock = threading.Lock()
        self.__restart_on_free = restart
        self.__pickle_proto = proto
        self.__connect_locks = {}

        # add local directory and sys.path to PYTHONPATH
        pythondirs = [os.getcwd()] + sys.path

        if "PYTHONPATH" in os.environ and os.environ["PYTHONPATH"]:
            pythondirs += os.environ["PYTHONPATH"].split(os.pathsep)
        os.environ["PYTHONPATH"] = os.pathsep.join(set(pythondirs))

        atexit.register(self.destroy)
        self.__stats = {"local": _Statistics(0)}
        self.set_ncpus(ncpus)

        self.ppservers = []
        self.auto_ppservers = []
        self.socket_timeout = socket_timeout

        for ppserver in ppservers:
            ppserver = ppserver.split(":")
            host = ppserver[0]
            if len(ppserver)>1:
                port = int(ppserver[1])
            else:
                port = ppcommon.randomport()
            if host.find("*") == -1:
                self.ppservers.append((host, port))
            else:
                if host == "*":
                    host = "*.*.*.*"
                interface = host.replace("*", "0")
                broadcast = host.replace("*", "255")
                self.auto_ppservers.append(((interface, port),
                        (broadcast, port)))
        self.__stats_lock = threading.Lock()
        if secret is not None:
            if not isinstance(secret, types.StringType):
                raise TypeError("secret must be of a string type")
            self.secret = str(secret)
        elif hasattr(user, "pp_secret"):
            secret = getattr(user, "pp_secret")
            if not isinstance(secret, types.StringType):
                raise TypeError("secret must be of a string type")
            self.secret = str(secret)
        else:
            self.secret = Server.default_secret
        self.__connect()
        self.__creation_time = time.time()
        self.logger.info("pp local server started with %d workers"
                % (self.__ncpus, ))

Example 29

Project: shopify_python_api Source File: test_helper.py
    def fake(self, endpoint, **kwargs):
        body = kwargs.pop('body', None) or self.load_fixture(endpoint)
        format = kwargs.pop('format','json')
        method = kwargs.pop('method','GET')

        if ('extension' in kwargs and not kwargs['extension']):
            extension = ""
        else:
            extension = ".%s" % (kwargs.pop('extension', 'json'))

        url = "https://this-is-my-test-show.myshopify.com/admin/%s%s" % (endpoint, extension)
        try:
           url = kwargs['url']
        except KeyError:
           pass

        headers = {}
        if kwargs.pop('has_user_agent', True):
            userAgent = 'ShopifyPythonAPI/%s Python/%s' % (shopify.VERSION, sys.version.split(' ', 1)[0])
            headers['User-agent'] = userAgent

        try:
            headers.update(kwargs['headers'])
        except KeyError:
           pass

        code = kwargs.pop('code', 200)

        self.http.respond_to(
          method, url, headers, body=body, code=code)

Example 30

Project: scons Source File: TestSCons_time.py
Function: init
    def __init__(self, **kw):
        """Initialize an SCons_time testing object.

        If they're not overridden by keyword arguments, this
        initializes the object with the following default values:

                program = 'scons-time'
                interpreter = ['python', '-tt']
                match = match_exact
                workdir = ''

        The workdir value means that, by default, a temporary workspace
        directory is created for a TestSCons_time environment.
        In addition, this method changes directory (chdir) to the
        workspace directory, so an explicit "chdir = '.'" on all of the
        run() method calls is not necessary.
        """

        self.orig_cwd = os.getcwd()
        try:
            script_dir = os.environ['SCONS_SCRIPT_DIR']
        except KeyError:
            pass
        else:
            os.chdir(script_dir)
        if 'program' not in kw:
            p = os.environ.get('SCONS_TIME')
            if not p:
                p = 'scons-time'
                if not os.path.exists(p):
                    p = 'scons-time.py'
            kw['program'] = p

        if 'interpreter' not in kw:
            kw['interpreter'] = [python, '-tt']

        if 'match' not in kw:
            kw['match'] = match_exact

        if 'workdir' not in kw:
            kw['workdir'] = ''

        TestCommon.__init__(self, **kw)

        # Now that the testing object has been set up, check if we should
        # skip the test due to the Python version.  We need to be able to
        # import __future__ (which scons-time.py uses for nested scopes)
        # and to handle list comprehensions (just because we're avoiding
        # the old map() and filter() idioms).

        try:
            import __future__
        except ImportError:
            version = sys.version.split()[0]
            msg = 'scons-time does not work on Python version %s\n' % version
            self.skip_test(msg)

        try:
            eval('[x for x in [1, 2]]')
        except SyntaxError:
            version = sys.version.split()[0]
            msg = 'scons-time does not work on Python version %s\n' % version
            self.skip_test(msg)

Example 31

Project: TACTIC Source File: test.py
    def run(self, conf=None):
        """Run the test harness (using the given [global] conf)."""
        import cherrypy
        v = sys.version.split()[0]
        print("Python version used to run this test script: %s" % v)
        print("CherryPy version: %s" % cherrypy.__version__)
        if self.supervisor.scheme == "https":
            ssl = " (ssl)"
        else:
            ssl = ""
        print("HTTP server version: %s%s" % (self.supervisor.protocol, ssl))
        print("PID: %s" % os.getpid())
        print("")
        
        cherrypy.server.using_apache = self.supervisor.using_apache
        cherrypy.server.using_wsgi = self.supervisor.using_wsgi
        
        if isinstance(conf, basestring):
            parser = cherrypy.config._Parser()
            conf = parser.dict_from_file(conf).get('global', {})
        else:
            conf = conf or {}
        baseconf = conf.copy()
        baseconf.update({'server.socket_host': self.supervisor.host,
                         'server.socket_port': self.supervisor.port,
                         'server.protocol_version': self.supervisor.protocol,
                         'environment': "test_suite",
                         })
        if self.supervisor.scheme == "https":
            baseconf['server.ssl_certificate'] = serverpem
            baseconf['server.ssl_private_key'] = serverpem
        
        # helper must be imported lazily so the coverage tool
        # can run against module-level statements within cherrypy.
        # Also, we have to do "from cherrypy.test import helper",
        # exactly like each test module does, because a relative import
        # would stick a second instance of webtest in sys.modules,
        # and we wouldn't be able to globally override the port anymore.
        from cherrypy.test import helper, webtest
        webtest.WebCase.interactive = self.interactive
        if self.supervisor.scheme == "https":
            webtest.WebCase.HTTP_CONN = HTTPSConnection
        print("")
        print("Running tests: %s" % self.supervisor)
        
        return helper.run_test_suite(self.tests, baseconf, self.supervisor)

Example 32

Project: sixcells Source File: common.py
    def about(self):
        try:
            import pulp
        except ImportError:
            pulp_version = "(missing!)"
        else:
            pulp_version = pulp.VERSION
        try:
            import sqlite3
        except ImportError:
            sqlite_version = "(missing!)"
        else:
            sqlite_version = sqlite3.sqlite_version
        
        QMessageBox.information(None, "About", """
            <h1>{}</h1>
            <h3>Version {}</h3>

            <p>&copy; 2014-2015 Oleh Prypin <<a href="mailto:[email protected]">[email protected]</a>><br/>
            &copy; 2014 Stefan Walzer <<a href="mailto:[email protected]">[email protected]</a>></p>

            <p>License: <a href="http://www.gnu.org/licenses/gpl.txt">GNU General Public License Version 3</a></p>

            Using:
            <ul>
            <li>Python {}
            <li>Qt {}
            <li>{} {}
            <li>PuLP {}
            <li>SQLite {}
            </ul>
        """.format(
            self.title, __version__,
            sys.version.split(' ', 1)[0],
            qt.version_str,
            qt.module, qt.module_version_str,
            pulp_version,
            sqlite_version,
        ))

Example 33

Project: st2 Source File: submit_debug_info.py
    @staticmethod
    def get_system_information():
        """
        Retrieve system information which is included in the report.

        :rtype: ``dict``
        """
        system_information = {
            'hostname': socket.gethostname(),
            'operating_system': {},
            'hardware': {
                'cpu': {},
                'memory': {}
            },
            'python': {},
            'stackstorm': {},
            'mistral': {}
        }

        # Operating system information
        system_information['operating_system']['system'] = platform.system()
        system_information['operating_system']['release'] = platform.release()
        system_information['operating_system']['operating_system'] = platform.platform()
        system_information['operating_system']['platform'] = platform.system()
        system_information['operating_system']['architecture'] = ' '.join(platform.architecture())

        if platform.system().lower() == 'linux':
            distribution = ' '.join(platform.linux_distribution())
            system_information['operating_system']['distribution'] = distribution

        system_information['python']['version'] = sys.version.split('\n')[0]

        # Hardware information
        cpu_info = get_cpu_info()

        if cpu_info:
            core_count = len(cpu_info)
            model = cpu_info[0]['model_name']
            system_information['hardware']['cpu'] = {
                'core_count': core_count,
                'model_name': model
            }
        else:
            # Unsupported platform
            system_information['hardware']['cpu'] = 'unsupported platform'

        memory_info = get_memory_info()

        if memory_info:
            total = memory_info['MemTotal'] / 1024
            free = memory_info['MemFree'] / 1024
            used = (total - free)
            system_information['hardware']['memory'] = {
                'total': total,
                'used': used,
                'free': free
            }
        else:
            # Unsupported platform
            system_information['hardware']['memory'] = 'unsupported platform'

        # StackStorm information
        system_information['stackstorm']['version'] = st2_version

        st2common_path = st2common.__file__
        st2common_path = os.path.dirname(st2common_path)

        if 'st2common/st2common' in st2common_path:
            # Assume we are running source install
            base_install_path = st2common_path.replace('/st2common/st2common', '')

            revision_hash = get_repo_latest_revision_hash(repo_path=base_install_path)

            system_information['stackstorm']['installation_method'] = 'source'
            system_information['stackstorm']['revision_hash'] = revision_hash
        else:
            package_list = get_package_list(name_startswith='st2')

            system_information['stackstorm']['installation_method'] = 'package'
            system_information['stackstorm']['packages'] = package_list

        # Mistral information
        repo_path = '/opt/openstack/mistral'
        revision_hash = get_repo_latest_revision_hash(repo_path=repo_path)
        system_information['mistral']['installation_method'] = 'source'
        system_information['mistral']['revision_hash'] = revision_hash

        return system_information

Example 34

Project: Py6S Source File: sixs.py
    def produce_debug_report(self):
        """Prints out information about the configuration of Py6S generally, and the current
        SixS object specifically, which will be useful when debugging problems."""
        import datetime
        import platform
        import sys

        print("Py6S Debugging Report")
        print("---------------------")
        print("Run on %s" % (str(datetime.datetime.now())))
        print("Platform: %s" % (platform.platform()))
        print("Python version: %s" % (sys.version.split('\n')[0]))
        print("Py6S version: %s" % (self.__version__))
        print("---------------------")
        self.test()
        print("---------------------")

        fname = self.write_input_file()
        with open(fname) as f:
            contents = f.readlines()

        print("".join(contents))

Example 35

Project: mezzanine Source File: runserver.py
def banner():

    # Database name - this is just the ``vendor`` atrribute of
    # the connection backend, with some exceptions where we
    # replace it with something else, such as microsoft -> sql server.
    conn = connection
    db_name = {
        "microsoft": "sql server",
    }.get(conn.vendor, conn.vendor)
    db_name = "%s%s" % (db_name[:1].upper(),
        db_name.replace("sql", "SQL").replace("db", "DB")[1:])

    # Database version - vendor names mapped to functions that
    # retrieve the version, which should be a sequence of things
    # to join with dots.
    db_version_func = {
        "postgresql": lambda: (
            conn.pg_version // 10000,
            conn.pg_version // 100 % 100,
            conn.pg_version % 100,
        ),
        "mysql": lambda: conn.mysql_version,
        "sqlite": lambda: conn.Database.sqlite_version_info,
        # The remaining backends haven't actually been tested,
        # and so their version logic has been gleaned from glancing
        # at the code for each backend.
        "oracle": lambda: [conn.oracle_version],
        "microsoft": lambda: [conn._DatabaseWrapper__get_dbms_version()],
        "firebird": lambda: conn.server_version.split(" ")[-1].split("."),
    }.get(conn.vendor, lambda: [])
    db_version = ".".join(map(str, db_version_func()))

    # The raw banner split into lines.
    lines = ("""

              .....
          _d^^^^^^^^^b_
       .d''           ``b.
     .p'                `q.
    .d'                   `b.
   .d'                     `b.   * Mezzanine %(mezzanine_version)s
   ::                       ::   * Django %(django_version)s
  ::    M E Z Z A N I N E    ::  * Python %(python_version)s
   ::                       ::   * %(db_name)s %(db_version)s
   `p.                     .q'   * %(os_name)s %(os_version)s
    `p.                   .q'
     `b.                 .d'
       `q..          ..p'
          ^q........p^
              ''''


""" % {
        "mezzanine_version": mezzanine.__version__,
        "django_version": django.get_version(),
        "python_version": sys.version.split(" ", 1)[0],
        "db_name": db_name,
        "db_version": db_version,
        "os_name": platform.system(),
        "os_version": platform.release(),
    }).splitlines()[2:]

    if not supports_color():
        return "\n".join(lines)

    # Pairs of function / colorize args for coloring the banner.
    # These are each of the states moving from left to right on
    # a single line of the banner. The function represents whether
    # the current char in a line should trigger the next state.
    color_states = [
        (lambda c: c != " ", {}),
        (lambda c: c == " ", {"fg": "red"}),
        (lambda c: c != " " and not c.isupper(),
            {"fg": "white", "bg": "red", "opts": ["bold"]}),
        (lambda c: c == " ", {"fg": "red"}),
        (lambda c: c == "*", {}),
        (lambda c: c != "*", {"fg": "red"}),
        (lambda c: False, {}),
    ]

    # Colorize the banner.
    for i, line in enumerate(lines):
        chars = []
        color_state = 0
        for char in line:
            color_state += color_states[color_state][0](char)
            chars.append(colorize(char, **color_states[color_state][1]))
        lines[i] = "".join(chars)

    return "\n".join(lines)

Example 36

Project: PokemonGo-Bot-Desktop Source File: cgitb.py
def text(einfo, context=5):
    """Return a plain text docuement describing a given traceback."""
    etype, evalue, etb = einfo
    if type(etype) is types.ClassType:
        etype = etype.__name__
    pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
    date = time.ctime(time.time())
    head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.
'''

    frames = []
    records = inspect.getinnerframes(etb, context)
    for frame, file, lnum, func, lines, index in records:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = 'in ' + func + \
                inspect.formatargvalues(args, varargs, varkw, locals,
                    formatvalue=lambda value: '=' + pydoc.text.repr(value))

        highlight = {}
        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try: return linecache.getline(file, lnum[0])
            finally: lnum[0] += 1
        vars = scanvars(reader, frame, locals)

        rows = [' %s %s' % (file, call)]
        if index is not None:
            i = lnum - index
            for line in lines:
                num = '%5d ' % i
                rows.append(num+line.rstrip())
                i += 1

        done, dump = {}, []
        for name, where, value in vars:
            if name in done: continue
            done[name] = 1
            if value is not __UNDEF__:
                if where == 'global': name = 'global ' + name
                elif where != 'local': name = where + name.split('.')[-1]
                dump.append('%s = %s' % (name, pydoc.text.repr(value)))
            else:
                dump.append(name + ' undefined')

        rows.append('\n'.join(dump))
        frames.append('\n%s\n' % '\n'.join(rows))

    exception = ['%s: %s' % (str(etype), str(evalue))]
    if isinstance(evalue, BaseException):
        for name in dir(evalue):
            value = pydoc.text.repr(getattr(evalue, name))
            exception.append('\n%s%s = %s' % (" "*4, name, value))

    return head + ''.join(frames) + ''.join(exception) + '''

The above is a description of an error in a Python program.  Here is
the original traceback:

%s
''' % ''.join(traceback.format_exception(etype, evalue, etb))

Example 37

Project: HTPC-Manager Source File: helper.py
    def _setup_server(cls, supervisor, conf):
        v = sys.version.split()[0]
        log.info("Python version used to run this test script: %s" % v)
        log.info("CherryPy version: %s" % cherrypy.__version__)
        if supervisor.scheme == "https":
            ssl = " (ssl)"
        else:
            ssl = ""
        log.info("HTTP server version: %s%s" % (supervisor.protocol, ssl))
        log.info("PID: %s" % os.getpid())

        cherrypy.server.using_apache = supervisor.using_apache
        cherrypy.server.using_wsgi = supervisor.using_wsgi

        if sys.platform[:4] == 'java':
            cherrypy.config.update({'server.nodelay': False})

        if isinstance(conf, basestring):
            parser = cherrypy.lib.reprconf.Parser()
            conf = parser.dict_from_file(conf).get('global', {})
        else:
            conf = conf or {}
        baseconf = conf.copy()
        baseconf.update({'server.socket_host': supervisor.host,
                         'server.socket_port': supervisor.port,
                         'server.protocol_version': supervisor.protocol,
                         'environment': "test_suite",
                         })
        if supervisor.scheme == "https":
            #baseconf['server.ssl_module'] = 'builtin'
            baseconf['server.ssl_certificate'] = serverpem
            baseconf['server.ssl_private_key'] = serverpem

        # helper must be imported lazily so the coverage tool
        # can run against module-level statements within cherrypy.
        # Also, we have to do "from cherrypy.test import helper",
        # exactly like each test module does, because a relative import
        # would stick a second instance of webtest in sys.modules,
        # and we wouldn't be able to globally override the port anymore.
        if supervisor.scheme == "https":
            webtest.WebCase.HTTP_CONN = HTTPSConnection
        return baseconf

Example 38

Project: Live-Blog Source File: core.py
Function: report_exception
    def report_Exception(self, error):
        if isinstance(error, utils.SystemMessage):
            self.report_SystemMessage(error)
        elif isinstance(error, UnicodeEncodeError):
            self.report_UnicodeError(error)
        elif isinstance(error, io.InputError):
            self._stderr.write('Unable to open source file for reading:\n'
                               '  %s\n' % ErrorString(error))
        elif isinstance(error, io.OutputError):
            self._stderr.write(
                'Unable to open destination file for writing:\n'
                '  %s\n' % ErrorString(error))
        else:
            print('%s' % ErrorString(error), file=self._stderr)
            print(("""\
Exiting due to error.  Use "--traceback" to diagnose.
Please report errors to <[email protected]>.
Include "--traceback" output, Docutils version (%s [%s]),
Python version (%s), your OS type & version, and the
command line used.""" % (__version__, __version_details__,
                         sys.version.split()[0])), file=self._stderr)

Example 39

Project: Live-Blog Source File: core.py
    def report_UnicodeError(self, error):
        data = error.object[error.start:error.end]
        self._stderr.write(
            '%s\n'
            '\n'
            'The specified output encoding (%s) cannot\n'
            'handle all of the output.\n'
            'Try setting "--output-encoding-error-handler" to\n'
            '\n'
            '* "xmlcharrefreplace" (for HTML & XML output);\n'
            '  the output will contain "%s" and should be usable.\n'
            '* "backslashreplace" (for other output formats);\n'
            '  look for "%s" in the output.\n'
            '* "replace"; look for "?" in the output.\n'
            '\n'
            '"--output-encoding-error-handler" is currently set to "%s".\n'
            '\n'
            'Exiting due to error.  Use "--traceback" to diagnose.\n'
            'If the advice above doesn\'t eliminate the error,\n'
            'please report it to <[email protected]>.\n'
            'Include "--traceback" output, Docutils version (%s),\n'
            'Python version (%s), your OS type & version, and the\n'
            'command line used.\n'
            % (ErrorString(error),
               self.settings.output_encoding,
               data.encode('ascii', 'xmlcharrefreplace'),
               data.encode('ascii', 'backslashreplace'),
               self.settings.output_encoding_error_handler,
               __version__, sys.version.split()[0]))

Example 40

Project: scalyr-agent-2 Source File: compiler.py
    def buildIndex(self, processedMibs, **options):
        comments = [
            'Produced by %s-%s at %s' % (packageName, packageVersion, time.asctime()),
            'On host %s platform %s version %s by user %s' % (hasattr(os, 'uname') and os.uname()[1] or '?', hasattr(os, 'uname') and os.uname()[0] or '?', hasattr(os, 'uname') and os.uname()[2] or '?', hasattr(os, 'getuid') and getpwuid(os.getuid())[0]) or '?',
            'Using Python version %s' % sys.version.split('\n')[0]
        ]
        try:
            self._writer.putData(
                self.indexFile,
                self._codegen.genIndex(
                    dict([(x, x.oid) for x in processedMibs if hasattr(x, 'oid')]),
                    comments=comments
                ),
                dryRun=options.get('dryRun')
            )
        except error.PySmiError:
            exc_class, exc, tb = sys.exc_info()
            exc.msg += ' at MIB index %s' % self.indexFile
            debug.logger & debug.flagCompiler and debug.logger('error %s when building %s' % (exc, self.indexFile))
            if options.get('ignoreErrors'):
                return
            if hasattr(exc, 'with_traceback'):
                raise exc.with_traceback(tb)
            else:
                raise exc

Example 41

Project: OmniMarkupPreviewer Source File: core.py
    def report_Exception(self, error):
        if isinstance(error, utils.SystemMessage):
            self.report_SystemMessage(error)
        elif isinstance(error, UnicodeEncodeError):
            self.report_UnicodeError(error)
        elif isinstance(error, io.InputError):
            self._stderr.write(u'Unable to open source file for reading:\n'
                               u'  %s\n' % ErrorString(error))
        elif isinstance(error, io.OutputError):
            self._stderr.write(
                u'Unable to open destination file for writing:\n'
                u'  %s\n' % ErrorString(error))
        else:
            print >>self._stderr, u'%s' % ErrorString(error)
            print >>self._stderr, ("""\
Exiting due to error.  Use "--traceback" to diagnose.
Please report errors to <[email protected]>.
Include "--traceback" output, Docutils version (%s [%s]),
Python version (%s), your OS type & version, and the
command line used.""" % (__version__, __version_details__,
                         sys.version.split()[0]))

Example 42

Project: jirash Source File: Server.py
Function: version_string
    def version_string(self):
        return '<a href="http://pywebsvcs.sf.net">' + \
            'SOAPpy ' + __version__ + '</a> (Python ' + \
            sys.version.split()[0] + ')'

Example 43

Project: scikit-learn Source File: format_stack.py
Function: format_exc
def format_exc(etype, evalue, etb, context=5, tb_offset=0):
    """ Return a nice text docuement describing the traceback.

        Parameters
        -----------
        etype, evalue, etb: as returned by sys.exc_info
        context: number of lines of the source file to plot
        tb_offset: the number of stack frame not to use (0 = use all)

    """
    # some locals
    try:
        etype = etype.__name__
    except AttributeError:
        pass

    # Header with the exception type, python version, and date
    pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
    date = time.ctime(time.time())
    pid = 'PID: %i' % os.getpid()

    head = '%s%s%s\n%s%s%s' % (
        etype, ' ' * (75 - len(str(etype)) - len(date)),
        date, pid, ' ' * (75 - len(str(pid)) - len(pyver)),
        pyver)

    # Drop topmost frames if requested
    try:
        records = _fixed_getframes(etb, context, tb_offset)
    except:
        raise
        print('\nUnfortunately, your original traceback can not be '
              'constructed.\n')
        return ''

    # Get (safely) a string form of the exception info
    try:
        etype_str, evalue_str = map(str, (etype, evalue))
    except:
        # User exception is improperly defined.
        etype, evalue = str, sys.exc_info()[:2]
        etype_str, evalue_str = map(str, (etype, evalue))
    # ... and format it
    exception = ['%s: %s' % (etype_str, evalue_str)]
    frames = format_records(records)
    return '%s\n%s\n%s' % (head, '\n'.join(frames), ''.join(exception[0]))

Example 44

Project: TrustRouter Source File: cgitb.py
def html(einfo, context=5):
    """Return a nice HTML docuement describing a given traceback."""
    etype, evalue, etb = einfo
    if isinstance(etype, type):
        etype = etype.__name__
    pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
    date = time.ctime(time.time())
    head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
        '<big><big>%s</big></big>' %
        strong(pydoc.html.escape(str(etype))),
        '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
<p>A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.</p>'''

    indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
    frames = []
    records = inspect.getinnerframes(etb, context)
    for frame, file, lnum, func, lines, index in records:
        if file:
            file = os.path.abspath(file)
            link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
        else:
            file = link = '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = 'in ' + strong(func) + \
                inspect.formatargvalues(args, varargs, varkw, locals,
                    formatvalue=lambda value: '=' + pydoc.html.repr(value))

        highlight = {}
        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try: return linecache.getline(file, lnum[0])
            finally: lnum[0] += 1
        vars = scanvars(reader, frame, locals)

        rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
                ('<big>&nbsp;</big>', link, call)]
        if index is not None:
            i = lnum - index
            for line in lines:
                num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
                if i in highlight:
                    line = '<tt>=>%s%s</tt>' % (num, pydoc.html.preformat(line))
                    rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
                else:
                    line = '<tt>&nbsp;&nbsp;%s%s</tt>' % (num, pydoc.html.preformat(line))
                    rows.append('<tr><td>%s</td></tr>' % grey(line))
                i += 1

        done, dump = {}, []
        for name, where, value in vars:
            if name in done: continue
            done[name] = 1
            if value is not __UNDEF__:
                if where in ('global', 'builtin'):
                    name = ('<em>%s</em> ' % where) + strong(name)
                elif where == 'local':
                    name = strong(name)
                else:
                    name = where + strong(name.split('.')[-1])
                dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
            else:
                dump.append(name + ' <em>undefined</em>')

        rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
        frames.append('''
<table width="100%%" cellspacing=0 cellpadding=0 border=0>
%s</table>''' % '\n'.join(rows))

    exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
                                pydoc.html.escape(str(evalue)))]
    for name in dir(evalue):
        if name[:1] == '_': continue
        value = pydoc.html.repr(getattr(evalue, name))
        exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))

    return head + ''.join(frames) + ''.join(exception) + '''


<!-- The above is a description of an error in a Python program, formatted
     for a Web browser because the 'cgitb' module was enabled.  In case you
     are not reading this in a Web browser, here is the original traceback:

%s
-->
''' % pydoc.html.escape(
          ''.join(traceback.format_exception(etype, evalue, etb)))

Example 45

Project: TrustRouter Source File: cgitb.py
def text(einfo, context=5):
    """Return a plain text docuement describing a given traceback."""
    etype, evalue, etb = einfo
    if isinstance(etype, type):
        etype = etype.__name__
    pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
    date = time.ctime(time.time())
    head = "%s\n%s\n%s\n" % (str(etype), pyver, date) + '''
A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.
'''

    frames = []
    records = inspect.getinnerframes(etb, context)
    for frame, file, lnum, func, lines, index in records:
        file = file and os.path.abspath(file) or '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = 'in ' + func + \
                inspect.formatargvalues(args, varargs, varkw, locals,
                    formatvalue=lambda value: '=' + pydoc.text.repr(value))

        highlight = {}
        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try: return linecache.getline(file, lnum[0])
            finally: lnum[0] += 1
        vars = scanvars(reader, frame, locals)

        rows = [' %s %s' % (file, call)]
        if index is not None:
            i = lnum - index
            for line in lines:
                num = '%5d ' % i
                rows.append(num+line.rstrip())
                i += 1

        done, dump = {}, []
        for name, where, value in vars:
            if name in done: continue
            done[name] = 1
            if value is not __UNDEF__:
                if where == 'global': name = 'global ' + name
                elif where != 'local': name = where + name.split('.')[-1]
                dump.append('%s = %s' % (name, pydoc.text.repr(value)))
            else:
                dump.append(name + ' undefined')

        rows.append('\n'.join(dump))
        frames.append('\n%s\n' % '\n'.join(rows))

    exception = ['%s: %s' % (str(etype), str(evalue))]
    for name in dir(evalue):
        value = pydoc.text.repr(getattr(evalue, name))
        exception.append('\n%s%s = %s' % (" "*4, name, value))

    return head + ''.join(frames) + ''.join(exception) + '''

The above is a description of an error in a Python program.  Here is
the original traceback:

%s
''' % ''.join(traceback.format_exception(etype, evalue, etb))

Example 46

Project: TrustRouter Source File: install.py
    def finalize_options(self):
        """Finalizes options."""
        # This method (and its pliant slaves, like 'finalize_unix()',
        # 'finalize_other()', and 'select_scheme()') is where the default
        # installation directories for modules, extension modules, and
        # anything else we care to install from a Python module
        # distribution.  Thus, this code makes a pretty important policy
        # statement about how third-party stuff is added to a Python
        # installation!  Note that the actual work of installation is done
        # by the relatively simple 'install_*' commands; they just take
        # their orders from the installation directory options determined
        # here.

        # Check for errors/inconsistencies in the options; first, stuff
        # that's wrong on any platform.

        if ((self.prefix or self.exec_prefix or self.home) and
            (self.install_base or self.install_platbase)):
            raise DistutilsOptionError(
                   "must supply either prefix/exec-prefix/home or " +
                   "install-base/install-platbase -- not both")

        if self.home and (self.prefix or self.exec_prefix):
            raise DistutilsOptionError(
                  "must supply either home or prefix/exec-prefix -- not both")

        if self.user and (self.prefix or self.exec_prefix or self.home or
                self.install_base or self.install_platbase):
            raise DistutilsOptionError("can't combine user with with prefix/"
                                       "exec_prefix/home or install_(plat)base")

        # Next, stuff that's wrong (or dubious) only on certain platforms.
        if os.name != "posix":
            if self.exec_prefix:
                self.warn("exec-prefix option ignored on this platform")
                self.exec_prefix = None

        # Now the interesting logic -- so interesting that we farm it out
        # to other methods.  The goal of these methods is to set the final
        # values for the install_{lib,scripts,data,...}  options, using as
        # input a heady brew of prefix, exec_prefix, home, install_base,
        # install_platbase, user-supplied versions of
        # install_{purelib,platlib,lib,scripts,data,...}, and the
        # INSTALL_SCHEME dictionary above.  Phew!

        self.dump_dirs("pre-finalize_{unix,other}")

        if os.name == 'posix':
            self.finalize_unix()
        else:
            self.finalize_other()

        self.dump_dirs("post-finalize_{unix,other}()")

        # Expand configuration variables, tilde, etc. in self.install_base
        # and self.install_platbase -- that way, we can use $base or
        # $platbase in the other installation directories and not worry
        # about needing recursive variable expansion (shudder).

        py_version = sys.version.split()[0]
        (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
        try:
            abiflags = sys.abiflags
        except AttributeError:
            # sys.abiflags may not be defined on all platforms.
            abiflags = ''
        self.config_vars = {'dist_name': self.distribution.get_name(),
                            'dist_version': self.distribution.get_version(),
                            'dist_fullname': self.distribution.get_fullname(),
                            'py_version': py_version,
                            'py_version_short': py_version[0:3],
                            'py_version_nodot': py_version[0] + py_version[2],
                            'sys_prefix': prefix,
                            'prefix': prefix,
                            'sys_exec_prefix': exec_prefix,
                            'exec_prefix': exec_prefix,
                            'abiflags': abiflags,
                           }

        if HAS_USER_SITE:
            self.config_vars['userbase'] = self.install_userbase
            self.config_vars['usersite'] = self.install_usersite

        self.expand_basedirs()

        self.dump_dirs("post-expand_basedirs()")

        # Now define config vars for the base directories so we can expand
        # everything else.
        self.config_vars['base'] = self.install_base
        self.config_vars['platbase'] = self.install_platbase

        if DEBUG:
            from pprint import pprint
            print("config vars:")
            pprint(self.config_vars)

        # Expand "~" and configuration variables in the installation
        # directories.
        self.expand_dirs()

        self.dump_dirs("post-expand_dirs()")

        # Create directories in the home dir:
        if self.user:
            self.create_home_path()

        # Pick the actual directory to install all modules to: either
        # install_purelib or install_platlib, depending on whether this
        # module distribution is pure or not.  Of course, if the user
        # already specified install_lib, use their selection.
        if self.install_lib is None:
            if self.distribution.ext_modules: # has extensions: non-pure
                self.install_lib = self.install_platlib
            else:
                self.install_lib = self.install_purelib


        # Convert directories from Unix /-separated syntax to the local
        # convention.
        self.convert_paths('lib', 'purelib', 'platlib',
                           'scripts', 'data', 'headers',
                           'userbase', 'usersite')

        # Well, we're not actually fully completely finalized yet: we still
        # have to deal with 'extra_path', which is the hack for allowing
        # non-packagized module distributions (hello, Numerical Python!) to
        # get their own directories.
        self.handle_extra_path()
        self.install_libbase = self.install_lib # needed for .pth file
        self.install_lib = os.path.join(self.install_lib, self.extra_dirs)

        # If a new root directory was supplied, make all the installation
        # dirs relative to it.
        if self.root is not None:
            self.change_roots('libbase', 'lib', 'purelib', 'platlib',
                              'scripts', 'data', 'headers')

        self.dump_dirs("after prepending root")

        # Find out the build directories, ie. where to install from.
        self.set_undefined_options('build',
                                   ('build_base', 'build_base'),
                                   ('build_lib', 'build_lib'))

Example 47

Project: PokemonGo-Bot-Desktop Source File: cgitb.py
def html(einfo, context=5):
    """Return a nice HTML docuement describing a given traceback."""
    etype, evalue, etb = einfo
    if type(etype) is types.ClassType:
        etype = etype.__name__
    pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
    date = time.ctime(time.time())
    head = '<body bgcolor="#f0f0f8">' + pydoc.html.heading(
        '<big><big>%s</big></big>' %
        strong(pydoc.html.escape(str(etype))),
        '#ffffff', '#6622aa', pyver + '<br>' + date) + '''
<p>A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.</p>'''

    indent = '<tt>' + small('&nbsp;' * 5) + '&nbsp;</tt>'
    frames = []
    records = inspect.getinnerframes(etb, context)
    for frame, file, lnum, func, lines, index in records:
        if file:
            file = os.path.abspath(file)
            link = '<a href="file://%s">%s</a>' % (file, pydoc.html.escape(file))
        else:
            file = link = '?'
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        call = ''
        if func != '?':
            call = 'in ' + strong(func) + \
                inspect.formatargvalues(args, varargs, varkw, locals,
                    formatvalue=lambda value: '=' + pydoc.html.repr(value))

        highlight = {}
        def reader(lnum=[lnum]):
            highlight[lnum[0]] = 1
            try: return linecache.getline(file, lnum[0])
            finally: lnum[0] += 1
        vars = scanvars(reader, frame, locals)

        rows = ['<tr><td bgcolor="#d8bbff">%s%s %s</td></tr>' %
                ('<big>&nbsp;</big>', link, call)]
        if index is not None:
            i = lnum - index
            for line in lines:
                num = small('&nbsp;' * (5-len(str(i))) + str(i)) + '&nbsp;'
                if i in highlight:
                    line = '<tt>=>%s%s</tt>' % (num, pydoc.html.preformat(line))
                    rows.append('<tr><td bgcolor="#ffccee">%s</td></tr>' % line)
                else:
                    line = '<tt>&nbsp;&nbsp;%s%s</tt>' % (num, pydoc.html.preformat(line))
                    rows.append('<tr><td>%s</td></tr>' % grey(line))
                i += 1

        done, dump = {}, []
        for name, where, value in vars:
            if name in done: continue
            done[name] = 1
            if value is not __UNDEF__:
                if where in ('global', 'builtin'):
                    name = ('<em>%s</em> ' % where) + strong(name)
                elif where == 'local':
                    name = strong(name)
                else:
                    name = where + strong(name.split('.')[-1])
                dump.append('%s&nbsp;= %s' % (name, pydoc.html.repr(value)))
            else:
                dump.append(name + ' <em>undefined</em>')

        rows.append('<tr><td>%s</td></tr>' % small(grey(', '.join(dump))))
        frames.append('''
<table width="100%%" cellspacing=0 cellpadding=0 border=0>
%s</table>''' % '\n'.join(rows))

    exception = ['<p>%s: %s' % (strong(pydoc.html.escape(str(etype))),
                                pydoc.html.escape(str(evalue)))]
    if isinstance(evalue, BaseException):
        for name in dir(evalue):
            if name[:1] == '_': continue
            value = pydoc.html.repr(getattr(evalue, name))
            exception.append('\n<br>%s%s&nbsp;=\n%s' % (indent, name, value))

    return head + ''.join(frames) + ''.join(exception) + '''


<!-- The above is a description of an error in a Python program, formatted
     for a Web browser because the 'cgitb' module was enabled.  In case you
     are not reading this in a Web browser, here is the original traceback:

%s
-->
''' % pydoc.html.escape(
          ''.join(traceback.format_exception(etype, evalue, etb)))

Example 48

Project: weberror Source File: formatter.py
    def format_collected_data(self, exc_data):
        impl = getDOMImplementation()
        newdoc = impl.createDocuement(None, "traceback", None)
        top_element = newdoc.docuementElement
        
        sysinfo = newdoc.createElement('sysinfo')
        language = create_text_node(newdoc, 'language', 'Python')
        language.attributes['version'] = sys.version.split(' ')[0]
        language.attributes['full_version'] = sys.version
        language.attributes['platform'] = sys.platform
        sysinfo.appendChild(language)
        
        # Pull out pkg_resource libraries for set libraries
        libs = get_libraries(self.extra_kwargs.get('libraries'))
        if libs:
            libraries = newdoc.createElement('libraries')
            for k, v in libs.iteritems():
                lib = newdoc.createElement('library')
                lib.attributes['version'] = v
                lib.attributes['name'] = k
                libraries.appendChild(lib)
            sysinfo.appendChild(libraries)
        
        top_element.appendChild(sysinfo)
        
        frames = self.filter_frames(exc_data.frames)
        stack = newdoc.createElement('stack')
        top_element.appendChild(stack)
        for frame in frames:
            xml_frame = newdoc.createElement('frame')
            stack.appendChild(xml_frame)
            
            filename = frame.filename
            if filename and self.trim_source_paths:
                for path, repl in self.trim_source_paths:
                    if filename.startswith(path):
                        filename = repl + filename[len(path):]
                        break
            self.format_source_line(filename or '?', frame, newdoc, xml_frame)
            
            source = frame.get_source_line()
            long_source = frame.get_source_line(2)
            if source:
                self.format_long_source(filename,
                    source.decode(frame.source_encoding, 'replace'),
                    long_source.decode(frame.source_encoding, 'replace'),
                    newdoc, xml_frame)
            
            # @@@ TODO: Put in a way to optionally toggle including variables
            # variables = newdoc.createElement('variables')
            # xml_frame.appendChild(variables)
            # for name, value in frame.locals.iteritems():
            #     if isinstance(value, unicode):
            #         value = value.encode('ascii', 'xmlcharrefreplace')
            #     variable = newdoc.createElement('variable')
            #     variable.appendChild(create_text_node(newdoc, 'name', name))
            #     variable.appendChild(create_text_node(newdoc, 'value', value))
            #     variables.appendChild(variable)
        
        etype = exc_data.exception_type
        if not isinstance(etype, basestring):
            etype = etype.__name__
        
        top_element.appendChild(self.format_exception_info(
            etype, exc_data.exception_value, newdoc, frame))
        return newdoc.toxml(), ''

Example 49

Project: qsnake Source File: ipy_profile_sh.py
Function: main
def main():
    ip = ipapi.get()
    o = ip.options
    # autocall to "full" mode (smart mode is default, I like full mode)
    
    o.autocall = 2
    
    # Jason Orendorff's path class is handy to have in user namespace
    # if you are doing shell-like stuff
    try:
        ip.ex("from path import path" )
    except ImportError:
        pass
    
    ip.ex('import os')
    ip.ex("def up(): os.chdir('..')")
        
    # Get pysh-like prompt for all profiles. 
    
    o.prompt_in1= '\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
    o.prompt_in2= '\C_Green|\C_LightGreen\D\C_Green> '
    o.prompt_out= '<\#> '
    
    from IPython import Release

    import sys
    # I like my banner minimal.
    o.banner = "Py %s IPy %s\n" % (sys.version.split('\n')[0],Release.version)
    
    # make 'd' an alias for ls -F
    
    ip.magic('alias d ls -F --color=auto')
    
    # Make available all system commands through "rehashing" immediately. 
    # You can comment these lines out to speed up startup on very slow 
    # machines, and to conserve a bit of memory. Note that pysh profile does this
    # automatically
    ip.IP.default_option('cd','-q')
    

    o.prompts_pad_left="1"
    # Remove all blank lines in between prompts, like a normal shell.
    o.separate_in="0"
    o.separate_out="0"
    o.separate_out2="0"
    
    # now alias all syscommands
    
    db = ip.db
    
    syscmds = db.get("syscmdlist",[] )
    if not syscmds:
        print textwrap.dedent("""
        System command list not initialized, probably the first run...
        running %rehashx to refresh the command list. Run %rehashx
        again to refresh command list (after installing new software etc.)
        """)
        ip.magic('rehashx')
        syscmds = db.get("syscmdlist")
    for cmd in syscmds:
        #print "al",cmd
        noext, ext = os.path.splitext(cmd)
        ip.IP.alias_table[noext] = (0,cmd)

Example 50

Project: sublime-robot-plugin Source File: version.py
Function: get_full_version
def get_full_version(who=''):
    sys_version = sys.version.split()[0]
    version = '%s %s (%s %s on %s)' \
        % (who, get_version(), _get_interpreter(), sys_version, sys.platform)
    return version.strip()
See More Examples - Go to Next Page
Page 1 Selected Page 2