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.

200 Examples 7

Example 1

Project: neuroConstruct
Source File: test_wsgiref.py
View license
    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 2

Project: openwrt-mt7620
Source File: test_wsgiref.py
View license
    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 3

Project: DragonPy
Source File: humanize.py
View license
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 4

Project: robotframework
Source File: version.py
View license
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 5

Project: pymo
Source File: test_wsgiref.py
View license
    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 6

Project: medicare-demo
Source File: test_wsgiref.py
View license
    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 7

Project: TrustRouter
Source File: test_wsgiref.py
View license
    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 8

Project: jmx4py
Source File: __main__.py
View license
@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 9

Project: ensembler
Source File: initproject.py
View license
    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 10

Project: chipsec
Source File: test_wsgiref.py
View license
    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 11

Project: RIDE
Source File: version.py
View license
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 12

Project: imagrium
Source File: test_wsgiref.py
View license
    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 13

Project: muddery
Source File: muddery_launcher.py
View license
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 14

Project: babble
Source File: test_wsgiref.py
View license
    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 15

Project: ensembler
Source File: initproject.py
View license
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 16

Project: jmx4py
Source File: test_cli.py
View license
@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 17

Project: lux
Source File: info.py
View license
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 18

Project: DragonPy
Source File: humanize.py
View license
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 19

Project: quicktill
Source File: managetill.py
View license
@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 20

Project: ensembler
Source File: initproject.py
View license
    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 21

Project: datafari
Source File: test_wsgiref.py
View license
    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 22

Project: py-generic-project
Source File: test_cli.py
View license
@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 23

Project: ganga
Source File: BOOT.py
View license
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 24

Project: pyvision
Source File: __init__.py
View license
    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 25

Project: brython
Source File: test_wsgiref.py
View license
    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 26

Project: openwrt-mt7620
Source File: test_wsgiref.py
View license
    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 27

Project: reprozip
Source File: graph.py
View license
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 28

Project: jmx4py
Source File: __main__.py
View license
@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 29

Project: qiime2
Source File: provenance.py
View license
    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 30

Project: TrustRouter
Source File: test_wsgiref.py
View license
    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 31

Project: PyAutoC
Source File: test_wsgiref.py
View license
    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 32

Project: gauged
Source File: bridge.py
View license
    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 33

Project: neuroConstruct
Source File: test_wsgiref.py
View license
    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 34

Project: muddery
Source File: muddery_launcher.py
View license
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 35

Project: jmx4py
Source File: test_cli.py
View license
@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 36

Project: mollie-api-python
Source File: Client.py
View license
    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 37

Project: wpbiff
Source File: cli.py
View license
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 38

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

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

Example 39

Project: bokeh
Source File: info.py
View license
    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 40

Project: pympler
Source File: run.py
View license
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 41

Project: GoAtThrottleUp
Source File: helper.py
View license
    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 42

Project: OmniMarkupPreviewer
Source File: core.py
View license
    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 43

Project: OmniMarkupPreviewer
Source File: core.py
View license
    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 44

Project: OmniMarkupPreviewer
Source File: core.py
View license
    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 45

Project: OmniMarkupPreviewer
Source File: core.py
View license
    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 46

Project: WAPT
Source File: cgitb.py
View license
def html(einfo, context=5):
    """Return a nice HTML document 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 47

Project: WAPT
Source File: cgitb.py
View license
def text(einfo, context=5):
    """Return a plain text document 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 48

Project: pymo
Source File: cgitb.py
View license
def html(einfo, context=5):
    """Return a nice HTML document 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 49

Project: qsnake
Source File: ipy_profile_sh.py
View license
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: scalyr-agent-2
Source File: compiler.py
View license
    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