Python sys.version() Examples
The following are 30
code examples of sys.version().
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 also want to check out all available functions/classes of the module
sys
, or try the search function
.
Example #1
Source File: section_cpu.py From HiSpatialCluster with Apache License 2.0 | 10 votes |
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 #2
Source File: request.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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 #3
Source File: versioneer.py From delocate with BSD 2-Clause "Simplified" License | 6 votes |
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 #4
Source File: service.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: app.py From datasette with Apache License 2.0 | 6 votes |
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 #6
Source File: platform.py From jawfish with MIT License | 6 votes |
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 #7
Source File: test_environment.py From Deep_Learning_Weather_Forecasting with Apache License 2.0 | 6 votes |
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 #8
Source File: cmd2plus.py From OpenTrader with GNU Lesser General Public License v3.0 | 6 votes |
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 #9
Source File: cmd2plus.py From OpenTrader with GNU Lesser General Public License v3.0 | 6 votes |
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 #10
Source File: misc.py From Pytorch-Project-Template with MIT License | 6 votes |
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 #11
Source File: diagnose.py From ServerlessCrawler-VancouverRealState with MIT License | 6 votes |
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 #12
Source File: request.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
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 #13
Source File: pkg_info.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
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 #14
Source File: platform.py From jawfish with MIT License | 6 votes |
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 #15
Source File: _version.py From delocate with BSD 2-Clause "Simplified" License | 6 votes |
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 #16
Source File: venv_update.py From mealpy with MIT License | 6 votes |
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 #17
Source File: venv_update.py From mealpy with MIT License | 6 votes |
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 #18
Source File: venv_update.py From mealpy with MIT License | 6 votes |
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 #19
Source File: diagnose.py From ServerlessCrawler-VancouverRealState with MIT License | 6 votes |
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
Source File: pydoc.py From jawfish with MIT License | 6 votes |
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 #21
Source File: diagnose.py From ServerlessCrawler-VancouverRealState with MIT License | 6 votes |
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 #22
Source File: tests.py From PythonClassBook with GNU General Public License v3.0 | 5 votes |
def test_value_python3(): import sys if sys.version[0] != "3": passed() return try: import_task_file() passed() except TypeError: failed("Division operator returns float in Python 3. Use int() function to convert float to integer.")
Example #23
Source File: decorator.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def decorate(func, caller, extras=()): """ decorate(func, caller) decorates a function using a caller. If the caller is a generator function, the resulting function will be a generator function. """ evaldict = dict(_call_=caller, _func_=func) es = '' for i, extra in enumerate(extras): ex = '_e%d_' % i evaldict[ex] = extra es += ex + ', ' if '3.5' <= sys.version < '3.6': # with Python 3.5 isgeneratorfunction returns True for all coroutines # however we know that it is NOT possible to have a generator # coroutine in python 3.5: PEP525 was not there yet generatorcaller = isgeneratorfunction( caller) and not iscoroutinefunction(caller) else: generatorcaller = isgeneratorfunction(caller) if generatorcaller: fun = FunctionMaker.create( func, "for res in _call_(_func_, %s%%(shortsignature)s):\n" " yield res" % es, evaldict, __wrapped__=func) else: fun = FunctionMaker.create( func, "return _call_(_func_, %s%%(shortsignature)s)" % es, evaldict, __wrapped__=func) if hasattr(func, '__qualname__'): fun.__qualname__ = func.__qualname__ return fun
Example #24
Source File: ElementTree.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def iselement(element): # FIXME: not sure about this; might be a better idea to look # for tag/attrib/text attributes return isinstance(element, _ElementInterface) or hasattr(element, "tag") ## # Writes an element tree or element structure to sys.stdout. This # function should be used for debugging only. # <p> # The exact output format is implementation dependent. In this # version, it's written as an ordinary XML file. # # @param elem An element tree or an individual element.
Example #25
Source File: configuration.py From faxplus-python with MIT License | 5 votes |
def to_debug_report(self): """Gets the essential information for debugging. :return: The report for debugging. """ return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ "Version of the API: 1.2.0\n"\ "SDK Package Version: 1.0".\ format(env=sys.platform, pyversion=sys.version)
Example #26
Source File: ElementTree.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def write(self, file, encoding="us-ascii"): assert self._root is not None if not hasattr(file, "write"): file = open(file, "wb") if not encoding: encoding = "us-ascii" elif encoding != "utf-8" and encoding != "us-ascii": file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding) self._write(file, self._root, encoding, {})
Example #27
Source File: client.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] if not hasattr(http_client, "HTTPSConnection"): raise NotImplementedError( "your version of http.client doesn't support HTTPS") # create a HTTPS connection object from a host descriptor # host may be a string, or a (host, x509-dict) tuple chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, http_client.HTTPSConnection(chost, None, **(x509 or {})) return self._connection[1] ## # Standard server proxy. This class establishes a virtual connection # to an XML-RPC server. # <p> # This class is available as ServerProxy and Server. New code should # use ServerProxy, to avoid confusion. # # @def ServerProxy(uri, **options) # @param uri The connection point on the server. # @keyparam transport A transport factory, compatible with the # standard transport class. # @keyparam encoding The default encoding used for 8-bit strings # (default is UTF-8). # @keyparam verbose Use a true value to enable debugging output. # (printed to standard output). # @see Transport
Example #28
Source File: aboutdlg.py From sk1-wx with GNU General Public License v3.0 | 5 votes |
def __init__(self, app, parent): wal.HPanel.__init__(self, parent) hp = wal.HPanel(self) self.pack(hp) hp.pack((55, 15)) logo_p = wal.VPanel(hp) hp.pack(logo_p, fill=True) logo_p.pack(get_bmp(logo_p, icons.SK1_ICON48), padding=5) hp.pack((10, 5)) box = wal.VPanel(hp) hp.pack(box, padding=5) data = app.appdata txt = data.app_name + ' - ' + _('vector graphics editor') box.pack(wal.Label(box, txt, True, 2), fill=True) data = app.appdata mark = '' if not data.build else ' %s %s' % (_('build'), data.build) txt = '%s: %s %s%s' % (_('Version'), data.version, data.revision, mark) box.pack(wal.Label(box, txt), fill=True) box.pack((35, 35)) import datetime year = str(datetime.date.today().year) txt = '(C) 2011-%s sK1 Project team' % year + '\n' box.pack(wal.Label(box, txt), fill=True) p = wal.HPanel(box) p.pack(wal.HyperlinkLabel(p, 'https://sk1project.net')) box.pack(p, fill=True)
Example #29
Source File: fusesocconfigparser.py From fusesoc with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, config_file): if sys.version[0] == "2": CP.__init__(self) else: super().__init__() if not os.path.exists(config_file): raise Exception("Could not find " + config_file) f = open(config_file) id_string = f.readline().split("=") if id_string[0].strip().upper() in ["CAPI", "SAPI"]: self.type = id_string[0] else: raise SyntaxError("Could not find API type in " + config_file) try: self.version = int(id_string[1].strip()) except ValueError: raise SyntaxError("Unknown version '{}'".format(id_string[1].strip())) except IndexError: raise SyntaxError("Could not find API version in " + config_file) if sys.version[0] == "2": exceptions = (configparser.ParsingError, configparser.DuplicateSectionError) else: exceptions = ( configparser.ParsingError, configparser.DuplicateSectionError, configparser.DuplicateOptionError, ) try: if sys.version[0] == "2": self.readfp(f) else: self.read_file(f) except configparser.MissingSectionHeaderError: raise SyntaxError("Missing section header") except exceptions as e: raise SyntaxError(e.message)
Example #30
Source File: client.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] if not hasattr(http_client, "HTTPSConnection"): raise NotImplementedError( "your version of http.client doesn't support HTTPS") # create a HTTPS connection object from a host descriptor # host may be a string, or a (host, x509-dict) tuple chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, http_client.HTTPSConnection(chost, None, **(x509 or {})) return self._connection[1] ## # Standard server proxy. This class establishes a virtual connection # to an XML-RPC server. # <p> # This class is available as ServerProxy and Server. New code should # use ServerProxy, to avoid confusion. # # @def ServerProxy(uri, **options) # @param uri The connection point on the server. # @keyparam transport A transport factory, compatible with the # standard transport class. # @keyparam encoding The default encoding used for 8-bit strings # (default is UTF-8). # @keyparam verbose Use a true value to enable debugging output. # (printed to standard output). # @see Transport