Python sys.version() Examples

The following are 30 code examples for showing how to use sys.version(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
Project: OpenTrader   Author: OpenTrading   File: cmd2plus.py    License: GNU Lesser General Public License v3.0 7 votes vote down vote up
def do_py(self, arg):
        '''
        py <command>: Executes a Python command.
        py: Enters interactive Python mode.
        End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, ``exit()``.
        Non-python commands can be issued with ``cmd("your command")``.
        Run python code from external files with ``run("filename.py")``
        '''
        self.pystate['self'] = self
        arg = arg.parsed.raw[2:].strip()
        localvars = (self.locals_in_py and self.pystate) or {}
        interp = InteractiveConsole(locals=localvars)
        interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')
        if arg.strip():
            interp.runcode(arg)
        else:
            def quit():
                raise EmbeddedConsoleExit
            def onecmd_plus_hooks(arg):
                return self.onecmd_plus_hooks(arg + '\n')
            def run(arg):
                try:
                    file = open(arg)
                    interp.runcode(file.read())
                    file.close()
                except IOError as e:
                    self.perror(e)
            self.pystate['quit'] = quit
            self.pystate['exit'] = quit
            self.pystate['cmd'] = onecmd_plus_hooks
            self.pystate['run'] = run
            try:
                cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
                keepstate = Statekeeper(sys, ('stdin','stdout'))
                sys.stdout = self.stdout
                sys.stdin = self.stdin
                interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" %
                       (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__))
            except EmbeddedConsoleExit:
                pass
            keepstate.restore() 
Example 2
Project: HiSpatialCluster   Author: lopp2005   File: section_cpu.py    License: Apache License 2.0 6 votes vote down vote up
def generate_cls_boundary(cls_input,cntr_id_field,boundary_output,cpu_core):
    arcpy.env.parallelProcessingFactor=cpu_core
    arcpy.SetProgressorLabel('Generating Delaunay Triangle...')
    arrays=arcpy.da.FeatureClassToNumPyArray(cls_input,['SHAPE@XY',cntr_id_field])
   
    cid_field_type=[f.type for f in arcpy.Describe(cls_input).fields if f.name==cntr_id_field][0]
    delaunay=Delaunay(arrays['SHAPE@XY']).simplices.copy()
    arcpy.CreateFeatureclass_management('in_memory','boundary_temp','POLYGON',spatial_reference=arcpy.Describe(cls_input).spatialReference)
    fc=r'in_memory\boundary_temp'
    arcpy.AddField_management(fc,cntr_id_field,cid_field_type)
    cursor = arcpy.da.InsertCursor(fc, [cntr_id_field,"SHAPE@"])
    arcpy.SetProgressor("step", "Copying Delaunay Triangle to Temp Layer...",0, delaunay.shape[0], 1)
    for tri in delaunay:
        arcpy.SetProgressorPosition()
        cid=arrays[cntr_id_field][tri[0]]
        if cid == arrays[cntr_id_field][tri[1]] and cid == arrays[cntr_id_field][tri[2]]:
            cursor.insertRow([cid,arcpy.Polygon(arcpy.Array([arcpy.Point(*arrays['SHAPE@XY'][i]) for i in tri]))])
    arcpy.SetProgressor('default','Merging Delaunay Triangle...')
    if '64 bit' in sys.version:
        arcpy.PairwiseDissolve_analysis(fc,boundary_output,cntr_id_field)
    else:
        arcpy.Dissolve_management(fc,boundary_output,cntr_id_field)
    arcpy.Delete_management(fc)
    
    return 
Example 3
Project: Deep_Learning_Weather_Forecasting   Author: BruceBinBoxing   File: test_environment.py    License: Apache License 2.0 6 votes vote down vote up
def main():
    system_major = sys.version_info.major
    if REQUIRED_PYTHON == "python":
        required_major = 2
    elif REQUIRED_PYTHON == "python3":
        required_major = 3
    else:
        raise ValueError("Unrecognized python interpreter: {}".format(
            REQUIRED_PYTHON))

    if system_major != required_major:
        raise TypeError(
            "This project requires Python {}. Found: Python {}".format(
                required_major, sys.version))
    else:
        print(">>> Development environment passes all tests!") 
Example 4
Project: Pytorch-Project-Template   Author: moemen95   File: misc.py    License: MIT License 6 votes vote down vote up
def print_cuda_statistics():
    logger = logging.getLogger("Cuda Statistics")
    import sys
    from subprocess import call
    import torch
    logger.info('__Python VERSION:  {}'.format(sys.version))
    logger.info('__pyTorch VERSION:  {}'.format(torch.__version__))
    logger.info('__CUDA VERSION')
    call(["nvcc", "--version"])
    logger.info('__CUDNN VERSION:  {}'.format(torch.backends.cudnn.version()))
    logger.info('__Number CUDA Devices:  {}'.format(torch.cuda.device_count()))
    logger.info('__Devices')
    call(["nvidia-smi", "--format=csv",
          "--query-gpu=index,name,driver_version,memory.total,memory.used,memory.free"])
    logger.info('Active CUDA Device: GPU {}'.format(torch.cuda.current_device()))
    logger.info('Available devices  {}'.format(torch.cuda.device_count()))
    logger.info('Current cuda device  {}'.format(torch.cuda.current_device())) 
Example 5
Project: delocate   Author: matthew-brett   File: versioneer.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def os_path_relpath(path, start=os.path.curdir):
    """Return a relative version of a path"""

    if not path:
        raise ValueError("no path specified")

    start_list = [x for x in os.path.abspath(start).split(os.path.sep) if x]
    path_list = [x for x in os.path.abspath(path).split(os.path.sep) if x]

    # Work out how much of the filepath is shared by start and path.
    i = len(os.path.commonprefix([start_list, path_list]))

    rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return os.path.curdir
    return os.path.join(*rel_list) 
Example 6
Project: delocate   Author: matthew-brett   File: _version.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_versions(default={"version": "unknown", "full": ""}, verbose=False):
    # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
    # __file__, we can work backwards from there to the root. Some
    # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
    # case we can only use expanded variables.

    variables = { "refnames": git_refnames, "full": git_full }
    ver = versions_from_expanded_variables(variables, tag_prefix, verbose)
    if ver:
        return ver

    try:
        root = os.path.abspath(__file__)
        # versionfile_source is the relative path from the top of the source
        # tree (where the .git directory might live) to this file. Invert
        # this to find the root from __file__.
        for i in range(len(versionfile_source.split("/"))):
            root = os.path.dirname(root)
    except NameError:
        return default

    return (versions_from_vcs(tag_prefix, root, verbose)
            or versions_from_parentdir(parentdir_prefix, root, verbose)
            or default) 
Example 7
Project: mealpy   Author: edmundmok   File: venv_update.py    License: MIT License 6 votes vote down vote up
def parseargs(argv):
    '''handle --help, --version and our double-equal ==options'''
    args = []
    options = {}
    key = None
    for arg in argv:
        if arg in DEFAULT_OPTION_VALUES:
            key = arg.strip('=').replace('-', '_')
            options[key] = ()
        elif key is None:
            args.append(arg)
        else:
            options[key] += (arg,)

    if set(args) & {'-h', '--help'}:
        print(__doc__, end='')
        exit(0)
    elif set(args) & {'-V', '--version'}:
        print(__version__)
        exit(0)
    elif args:
        exit('invalid option: %s\nTry --help for more information.' % args[0])

    return options 
Example 8
Project: mealpy   Author: edmundmok   File: venv_update.py    License: MIT License 6 votes vote down vote up
def invalid_virtualenv_reason(venv_path, source_python, destination_python, options):
    try:
        orig_path = get_original_path(venv_path)
    except CalledProcessError:
        return 'could not inspect metadata'
    if not samefile(orig_path, venv_path):
        return 'virtualenv moved %s -> %s' % (timid_relpath(orig_path), timid_relpath(venv_path))
    elif has_system_site_packages(destination_python) != options.system_site_packages:
        return 'system-site-packages changed, to %s' % options.system_site_packages

    if source_python is None:
        return
    destination_version = get_python_version(destination_python)
    source_version = get_python_version(source_python)
    if source_version != destination_version:
        return 'python version changed %s -> %s' % (destination_version, source_version) 
Example 9
Project: mealpy   Author: edmundmok   File: venv_update.py    License: MIT License 6 votes vote down vote up
def pip_faster(venv_path, pip_command, install, bootstrap_deps):
    """install and run pip-faster"""
    # activate the virtualenv
    execfile_(venv_executable(venv_path, 'activate_this.py'))

    # disable a useless warning
    # FIXME: ensure a "true SSLContext" is available
    from os import environ
    environ['PIP_DISABLE_PIP_VERSION_CHECK'] = '1'

    # we always have to run the bootstrap, because the presense of an
    # executable doesn't imply the right version. pip is able to validate the
    # version in the fastpath case quickly anyway.
    run(('pip', 'install') + bootstrap_deps)

    run(pip_command + install) 
Example 10
Project: jawfish   Author: war-and-code   File: pydoc.py    License: MIT License 6 votes vote down vote up
def intro(self):
        self.output.write('''
Welcome to Python %s!  This is the interactive help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/%s/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
''' % tuple([sys.version[:3]]*2)) 
Example 11
Project: jawfish   Author: war-and-code   File: platform.py    License: MIT License 6 votes vote down vote up
def _norm_version(version, build=''):

    """ Normalize the version and build strings and return a single
        version string using the format major.minor.build (or patchlevel).
    """
    l = version.split('.')
    if build:
        l.append(build)
    try:
        ints = map(int,l)
    except ValueError:
        strings = l
    else:
        strings = list(map(str,ints))
    version = '.'.join(strings[:3])
    return version 
Example 12
Project: jawfish   Author: war-and-code   File: platform.py    License: MIT License 6 votes vote down vote up
def mac_ver(release='',versioninfo=('','',''),machine=''):

    """ Get MacOS version information and return it as tuple (release,
        versioninfo, machine) with versioninfo being a tuple (version,
        dev_stage, non_release_version).

        Entries which cannot be determined are set to the parameter values
        which default to ''. All tuple entries are strings.
    """

    # First try reading the information from an XML file which should
    # always be present
    info = _mac_ver_xml()
    if info is not None:
        return info

    # If that doesn't work for some reason fall back to reading the
    # information using gestalt calls.
    info = _mac_ver_gestalt()
    if info is not None:
        return info

    # If that also doesn't work return the default values
    return release,versioninfo,machine 
Example 13
Project: OpenTrader   Author: OpenTrading   File: cmd2plus.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def onecmd(self, line):
        """Interpret the argument as though it had been typed in response
        to the prompt.

        This may be overridden, but should not normally need to be;
        see the precmd() and postcmd() methods for useful execution hooks.
        The return value is a flag indicating whether interpretation of
        commands by the interpreter should stop.

        This (`cmd2`) version of `onecmd` already override's `cmd`'s `onecmd`.

        """
        statement = self.parsed(line)
        self.lastcmd = statement.parsed.raw
        funcname = self.func_named(statement.parsed.command)
        if not funcname:
            return self._default(statement)
        try:
            func = getattr(self, funcname)
        except AttributeError:
            return self._default(statement)
        stop = func(statement)
        return stop 
Example 14
Project: verge3d-blender-addon   Author: Soft8Soft   File: request.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, proxies=None, **x509):
        msg = "%(class)s style of invoking requests is deprecated. " \
              "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
        warnings.warn(msg, DeprecationWarning, stacklevel=3)
        if proxies is None:
            proxies = getproxies()
        assert hasattr(proxies, 'keys'), "proxies must be a mapping"
        self.proxies = proxies
        self.key_file = x509.get('key_file')
        self.cert_file = x509.get('cert_file')
        self.addheaders = [('User-Agent', self.version)]
        self.__tempfiles = []
        self.__unlink = os.unlink # See cleanup()
        self.tempcache = None
        # Undocumented feature: if you assign {} to tempcache,
        # it is used to cache files retrieved with
        # self.retrieve().  This is not enabled by default
        # since it does not work for changing documents (and I
        # haven't got the logic to check expiration headers
        # yet).
        self.ftpcache = ftpcache
        # Undocumented feature: you can use a different
        # ftp cache by assigning to the .ftpcache member;
        # in case you want logically independent URL openers
        # XXX This is not threadsafe.  Bah. 
Example 15
Project: me-ica   Author: ME-ICA   File: pkg_info.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def get_pkg_info(pkg_path):
    ''' Return dict describing the context of this package

    Parameters
    ----------
    pkg_path : str
       path containing __init__.py for package

    Returns
    -------
    context : dict
       with named parameters of interest
    '''
    src, hsh = pkg_commit_hash(pkg_path)
    import numpy
    return dict(
        pkg_path=pkg_path,
        commit_source=src,
        commit_hash=hsh,
        sys_version=sys.version,
        sys_executable=sys.executable,
        sys_platform=sys.platform,
        np_version=numpy.__version__) 
Example 16
Project: misp42splunk   Author: remg427   File: request.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, proxies=None, **x509):
        msg = "%(class)s style of invoking requests is deprecated. " \
              "Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
        warnings.warn(msg, DeprecationWarning, stacklevel=3)
        if proxies is None:
            proxies = getproxies()
        assert hasattr(proxies, 'keys'), "proxies must be a mapping"
        self.proxies = proxies
        self.key_file = x509.get('key_file')
        self.cert_file = x509.get('cert_file')
        self.addheaders = [('User-Agent', self.version)]
        self.__tempfiles = []
        self.__unlink = os.unlink # See cleanup()
        self.tempcache = None
        # Undocumented feature: if you assign {} to tempcache,
        # it is used to cache files retrieved with
        # self.retrieve().  This is not enabled by default
        # since it does not work for changing documents (and I
        # haven't got the logic to check expiration headers
        # yet).
        self.ftpcache = ftpcache
        # Undocumented feature: you can use a different
        # ftp cache by assigning to the .ftpcache member;
        # in case you want logically independent URL openers
        # XXX This is not threadsafe.  Bah. 
Example 17
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: diagnose.py    License: MIT License 6 votes vote down vote up
def diagnose(data):
    """Diagnostic suite for isolating common problems."""
    print "Diagnostic running on Beautiful Soup %s" % __version__
    print "Python version %s" % sys.version

    basic_parsers = ["html.parser", "html5lib", "lxml"]
    for name in basic_parsers:
        for builder in builder_registry.builders:
            if name in builder.features:
                break
        else:
            basic_parsers.remove(name)
            print (
                "I noticed that %s is not installed. Installing it may help." %
                name)

    if 'lxml' in basic_parsers:
        basic_parsers.append(["lxml", "xml"])
        try:
            from lxml import etree
            print "Found lxml version %s" % ".".join(map(str,etree.LXML_VERSION))
        except ImportError, e:
            print (
                "lxml is not installed or couldn't be imported.") 
Example 18
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: diagnose.py    License: MIT License 6 votes vote down vote up
def diagnose(data):
    """Diagnostic suite for isolating common problems."""
    print "Diagnostic running on Beautiful Soup %s" % __version__
    print "Python version %s" % sys.version

    basic_parsers = ["html.parser", "html5lib", "lxml"]
    for name in basic_parsers:
        for builder in builder_registry.builders:
            if name in builder.features:
                break
        else:
            basic_parsers.remove(name)
            print (
                "I noticed that %s is not installed. Installing it may help." %
                name)

    if 'lxml' in basic_parsers:
        basic_parsers.append(["lxml", "xml"])
        try:
            from lxml import etree
            print "Found lxml version %s" % ".".join(map(str,etree.LXML_VERSION))
        except ImportError, e:
            print (
                "lxml is not installed or couldn't be imported.") 
Example 19
Project: ServerlessCrawler-VancouverRealState   Author: MarcelloLins   File: diagnose.py    License: MIT License 6 votes vote down vote up
def diagnose(data):
    """Diagnostic suite for isolating common problems."""
    print "Diagnostic running on Beautiful Soup %s" % __version__
    print "Python version %s" % sys.version

    basic_parsers = ["html.parser", "html5lib", "lxml"]
    for name in basic_parsers:
        for builder in builder_registry.builders:
            if name in builder.features:
                break
        else:
            basic_parsers.remove(name)
            print (
                "I noticed that %s is not installed. Installing it may help." %
                name)

    if 'lxml' in basic_parsers:
        basic_parsers.append(["lxml", "xml"])
        try:
            from lxml import etree
            print "Found lxml version %s" % ".".join(map(str,etree.LXML_VERSION))
        except ImportError, e:
            print (
                "lxml is not installed or couldn't be imported.") 
Example 20
Project: plugin.video.emby   Author: MediaBrowser   File: service.py    License: GNU General Public License v3.0 6 votes vote down vote up
def check_version(self):

        ''' Check the database version to ensure we do not need to do a reset.
        '''
        with Database('emby') as embydb:

            version = emby_db.EmbyDatabase(embydb.cursor).get_version()
            LOG.info("---[ db/%s ]", version)

        if version and compare_version(version, "3.1.0") < 0:
            resp = dialog("yesno", heading=_('addon_name'), line1=_(33022))

            if not resp:

                LOG.warn("Database version is out of date! USER IGNORED!")
                dialog("ok", heading=_('addon_name'), line1=_(33023))

                raise Exception("User backed out of a required database reset")
            else:
                reset()

                raise Exception("Completed database reset") 
Example 21
Project: datasette   Author: simonw   File: app.py    License: Apache License 2.0 6 votes vote down vote up
def _plugins(self, request=None, all=False):
        ps = list(get_plugins())
        should_show_all = False
        if request is not None:
            should_show_all = request.args.get("all")
        else:
            should_show_all = all
        if not should_show_all:
            ps = [p for p in ps if p["name"] not in DEFAULT_PLUGINS]
        return [
            {
                "name": p["name"],
                "static": p["static_path"] is not None,
                "templates": p["templates_path"] is not None,
                "version": p.get("version"),
                "hooks": p["hooks"],
            }
            for p in ps
        ] 
Example 22
Project: aospy   Author: spencerahill   File: test_tutorial.py    License: Apache License 2.0 5 votes vote down vote up
def test_tutorial_notebook():
    pytest.importorskip('nbformat')
    pytest.importorskip('nbconvert')
    pytest.importorskip('matplotlib')

    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor

    rootdir = os.path.join(aospy.__path__[0], 'examples')
    with open(os.path.join(rootdir, 'tutorial.ipynb')) as nb_file:
        notebook = nbformat.read(nb_file, as_version=nbformat.NO_CONVERT)
    kernel_name = 'python' + str(sys.version[0])
    ep = ExecutePreprocessor(kernel_name=kernel_name)
    with warnings.catch_warnings(record=True):
        ep.preprocess(notebook, {}) 
Example 23
Project: cherrypy   Author: cherrypy   File: sessiondemo.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def page(self):
        changemsg = []
        if cherrypy.session.id != cherrypy.session.originalid:
            if cherrypy.session.originalid is None:
                changemsg.append(
                    'Created new session because no session id was given.')
            if cherrypy.session.missing:
                changemsg.append(
                    'Created new session due to missing '
                    '(expired or malicious) session.')
            if cherrypy.session.regenerated:
                changemsg.append('Application generated a new session.')

        try:
            expires = cherrypy.response.cookie['session_id']['expires']
        except KeyError:
            expires = ''

        return page % {
            'sessionid': cherrypy.session.id,
            'changemsg': '<br>'.join(changemsg),
            'respcookie': cherrypy.response.cookie.output(),
            'reqcookie': cherrypy.request.cookie.output(),
            'sessiondata': list(cherrypy.session.items()),
            'servertime': (
                datetime.utcnow().strftime('%Y/%m/%d %H:%M') + ' UTC'
            ),
            'serverunixtime': calendar.timegm(datetime.utcnow().timetuple()),
            'cpversion': cherrypy.__version__,
            'pyversion': sys.version,
            'expires': expires,
        } 
Example 24
Project: HiSpatialCluster   Author: lopp2005   File: tool_findnrstdist.py    License: Apache License 2.0 5 votes vote down vote up
def execute(self, parameters, messages):
        input_feature=parameters[0].valueAsText 
        id_field=parameters[1].valueAsText
        dens_field=parameters[2].valueAsText
        output_feature=parameters[3].valueAsText
        calc_device=parameters[4].valueAsText
        
        if '64 bit' not in sys.version and calc_device=='GPU':
            arcpy.AddError('Platform is 32bit and has no support for GPU/CUDA.')
            return

        arcpy.SetProgressorLabel('Calculating Point with Higher Density ...')
        
        arrays=arcpy.da.FeatureClassToNumPyArray(input_feature,[id_field,'SHAPE@X','SHAPE@Y',dens_field])
        
        results=0
        if calc_device=='GPU':
            from section_gpu import calc_nrst_dist_gpu
            results=calc_nrst_dist_gpu(arrays[id_field],arrays['SHAPE@X'],arrays['SHAPE@Y'],arrays[dens_field])
        else:
            from section_cpu import calc_nrst_dist_cpu
            results=calc_nrst_dist_cpu(arrays[id_field],arrays['SHAPE@X'],arrays['SHAPE@Y'],arrays[dens_field],parameters[5].value)
        
        struct_arrays=recfunctions.append_fields(recfunctions.append_fields(recfunctions.append_fields(arrays,'NRSTDIST',data=results[0])\
                                                                            ,'PARENTID',data=results[1])\
                                                 ,'MULTIPLY',data=results[0]*arrays[dens_field],usemask=False)            
#        if '64 bit' in sys.version and id_field==arcpy.Describe(input_feature).OIDFieldName:
#            sadnl=list(struct_arrays.dtype.names)
#            sadnl[sadnl.index(id_field)]='OID@'
#            struct_arrays.dtype.names=tuple(sadnl)
            
        arcpy.da.NumPyArrayToFeatureClass(struct_arrays,output_feature,\
                                          ('SHAPE@X','SHAPE@Y'),arcpy.Describe(input_feature).spatialReference)   
            
        return 
Example 25
Project: delocate   Author: matthew-brett   File: versioneer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % args[0])
                print(e)
            return None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None
    stdout = p.communicate()[0].strip()
    if sys.version >= '3':
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % args[0])
        return None
    return stdout 
Example 26
Project: delocate   Author: matthew-brett   File: versioneer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def versions_from_expanded_variables(variables, tag_prefix, verbose=False):
    refnames = variables["refnames"].strip()
    if refnames.startswith("$Format"):
        if verbose:
            print("variables are unexpanded, not using")
        return {} # unexpanded, so not in an unpacked git-archive tarball
    refs = set([r.strip() for r in refnames.strip("()").split(",")])
    # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
    # just "foo-1.0". If we see a "tag: " prefix, prefer those.
    TAG = "tag: "
    tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
    if not tags:
        # Either we're using git < 1.8.3, or there really are no tags. We use
        # a heuristic: assume all version tags have a digit. The old git %d
        # expansion behaves like git log --decorate=short and strips out the
        # refs/heads/ and refs/tags/ prefixes that would let us distinguish
        # between branches and tags. By ignoring refnames without digits, we
        # filter out many common branch names like "release" and
        # "stabilization", as well as "HEAD" and "master".
        tags = set([r for r in refs if re.search(r'\d', r)])
        if verbose:
            print("discarding '%s', no digits" % ",".join(refs-tags))
    if verbose:
        print("likely tags: %s" % ",".join(sorted(tags)))
    for ref in sorted(tags):
        # sorting will prefer e.g. "2.0" over "2.0rc1"
        if ref.startswith(tag_prefix):
            r = ref[len(tag_prefix):]
            if verbose:
                print("picking %s" % r)
            return { "version": r,
                     "full": variables["full"].strip() }
    # no suitable tags, so we use the full revision id
    if verbose:
        print("no suitable tags, using full revision id")
    return { "version": variables["full"].strip(),
             "full": variables["full"].strip() } 
Example 27
Project: delocate   Author: matthew-brett   File: versioneer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def versions_from_vcs(tag_prefix, root, verbose=False):
    # this runs 'git' from the root of the source tree. This only gets called
    # if the git-archive 'subst' variables were *not* expanded, and
    # _version.py hasn't already been rewritten with a short version string,
    # meaning we're inside a checked out source tree.

    if not os.path.exists(os.path.join(root, ".git")):
        if verbose:
            print("no .git in %s" % root)
        return {}

    GITS = ["git"]
    if sys.platform == "win32":
        GITS = ["git.cmd", "git.exe"]
    stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"],
                         cwd=root)
    if stdout is None:
        return {}
    if not stdout.startswith(tag_prefix):
        if verbose:
            print("tag '%s' doesn't start with prefix '%s'" % (stdout, tag_prefix))
        return {}
    tag = stdout[len(tag_prefix):]
    stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
    if stdout is None:
        return {}
    full = stdout.strip()
    if tag.endswith("-dirty"):
        full += "-dirty"
    return {"version": tag, "full": full} 
Example 28
Project: delocate   Author: matthew-brett   File: versioneer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
    # Source tarballs conventionally unpack into a directory that includes
    # both the project name and a version string.
    dirname = os.path.basename(root)
    if not dirname.startswith(parentdir_prefix):
        if verbose:
            print("guessing rootdir is '%s', but '%s' doesn't start with prefix '%s'" %
                  (root, dirname, parentdir_prefix))
        return None
    return {"version": dirname[len(parentdir_prefix):], "full": ""} 
Example 29
Project: delocate   Author: matthew-brett   File: versioneer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def write_to_version_file(filename, versions):
    f = open(filename, "w")
    f.write(SHORT_VERSION_PY % versions)
    f.close()
    print("set %s to '%s'" % (filename, versions["version"])) 
Example 30
Project: delocate   Author: matthew-brett   File: versioneer.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_version(verbose=False):
    return get_versions(verbose=verbose)["version"]