code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _process_args(self, largs, rargs, values): """_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in 'largs'. """ while rargs: arg = rargs[0] # We handle bare "--" explicitly, and bare "-" is handled by the # standard arg handler since the short arg case ensures that the # len of the opt string is greater than 1. if arg == "--": del rargs[0] return elif arg[0:2] == "--": # process a single long option (possibly with value(s)) self._process_long_opt(rargs, values) elif arg[:1] == "-" and len(arg) > 1: # process a cluster of short options (possibly with # value(s) for the last one only) self._process_short_opts(rargs, values) elif self.allow_interspersed_args: largs.append(arg) del rargs[0] else: return # stop now, leave this arg in rargs # Say this is the original argument list: # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] # ^ # (we are about to process arg(i)). # # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of # [arg0, ..., arg(i-1)] (any options and their arguments will have # been removed from largs). # # The while loop will usually consume 1 or more arguments per pass. # If it consumes 1 (eg. arg is an option that takes no arguments), # then after _process_arg() is done the situation is: # # largs = subset of [arg0, ..., arg(i)] # rargs = [arg(i+1), ..., arg(N-1)] # # If allow_interspersed_args is false, largs will always be # *empty* -- still a subset of [arg0, ..., arg(i-1)], but # not a very interesting subset!
_process_args(largs : [string], rargs : [string], values : Values) Process command-line arguments and populate 'values', consuming options and arguments from 'rargs'. If 'allow_interspersed_args' is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in 'largs'.
_process_args
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def error(self, msg): """error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ self.print_usage(sys.stderr) self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception.
error
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def print_usage(self, file=None): """print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to 'file' (default stdout). Any occurrence of the string "%prog" in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined. """ if self.usage: print >>file, self.get_usage()
print_usage(file : file = stdout) Print the usage message for the current program (self.usage) to 'file' (default stdout). Any occurrence of the string "%prog" in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined.
print_usage
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def print_version(self, file=None): """print_version(file : file = stdout) Print the version message for this program (self.version) to 'file' (default stdout). As with print_usage(), any occurrence of "%prog" in self.version is replaced by the current program's name. Does nothing if self.version is empty or undefined. """ if self.version: print >>file, self.get_version()
print_version(file : file = stdout) Print the version message for this program (self.version) to 'file' (default stdout). As with print_usage(), any occurrence of "%prog" in self.version is replaced by the current program's name. Does nothing if self.version is empty or undefined.
print_version
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def print_help(self, file=None): """print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout). """ if file is None: file = sys.stdout encoding = self._get_encoding(file) file.write(self.format_help().encode(encoding, "replace"))
print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout).
print_help
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def _match_abbrev(s, wordmap): """_match_abbrev(s : string, wordmap : {string : Option}) -> string Return the string key in 'wordmap' for which 's' is an unambiguous abbreviation. If 's' is found to be ambiguous or doesn't match any of 'words', raise BadOptionError. """ # Is there an exact match? if s in wordmap: return s else: # Isolate all words with s as a prefix. possibilities = [word for word in wordmap.keys() if word.startswith(s)] # No exact match, so there had better be just one possibility. if len(possibilities) == 1: return possibilities[0] elif not possibilities: raise BadOptionError(s) else: # More than one possible completion: ambiguous prefix. possibilities.sort() raise AmbiguousOptionError(s, possibilities)
_match_abbrev(s : string, wordmap : {string : Option}) -> string Return the string key in 'wordmap' for which 's' is an unambiguous abbreviation. If 's' is found to be ambiguous or doesn't match any of 'words', raise BadOptionError.
_match_abbrev
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/optparse.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/optparse.py
MIT
def makedirs(name, mode=0777): """makedirs(path [, mode=0777]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. """ head, tail = path.split(name) if not tail: head, tail = path.split(head) if head and tail and not path.exists(head): try: makedirs(head, mode) except OSError, e: # be happy if someone already created the path if e.errno != errno.EEXIST: raise if tail == curdir: # xxx/newdir/. exists if xxx/newdir exists return mkdir(name, mode)
makedirs(path [, mode=0777]) Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive.
makedirs
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def removedirs(name): """removedirs(path) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. Errors during this latter phase are ignored -- they generally mean that a directory was not empty. """ rmdir(name) head, tail = path.split(name) if not tail: head, tail = path.split(head) while head and tail: try: rmdir(head) except error: break head, tail = path.split(head)
removedirs(path) Super-rmdir; remove a leaf directory and all empty intermediate ones. Works like rmdir except that, if the leaf directory is successfully removed, directories corresponding to rightmost path segments will be pruned away until either the whole path is consumed or an error occurs. Errors during this latter phase are ignored -- they generally mean that a directory was not empty.
removedirs
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def renames(old, new): """renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned until either the whole path is consumed or a nonempty directory is found. Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file. """ head, tail = path.split(new) if head and tail and not path.exists(head): makedirs(head) rename(old, new) head, tail = path.split(old) if head and tail: try: removedirs(head) except error: pass
renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned until either the whole path is consumed or a nonempty directory is found. Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file.
renames
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def walk(top, topdown=True, onerror=None, followlinks=False): """Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. By default errors from the os.listdir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an os.error instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument 'followlinks' to true. Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Example: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories """ islink, join, isdir = path.islink, path.join, path.isdir # We may not have read permission for top, in which case we can't # get a list of the files the directory contains. os.path.walk # always suppressed the exception then, rather than blow up for a # minor reason when (say) a thousand readable directories are still # left to visit. That logic is copied here. try: # Note that listdir and error are globals in this module due # to earlier import-*. names = listdir(top) except error, err: if onerror is not None: onerror(err) return dirs, nondirs = [], [] for name in names: if isdir(join(top, name)): dirs.append(name) else: nondirs.append(name) if topdown: yield top, dirs, nondirs for name in dirs: new_path = join(top, name) if followlinks or not islink(new_path): for x in walk(new_path, topdown, onerror, followlinks): yield x if not topdown: yield top, dirs, nondirs
Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. By default errors from the os.listdir() call are ignored. If optional arg 'onerror' is specified, it should be a function; it will be called with one argument, an os.error instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, os.walk does not follow symbolic links to subdirectories on systems that support them. In order to get this functionality, set the optional argument 'followlinks' to true. Caution: if you pass a relative pathname for top, don't change the current working directory between resumptions of walk. walk never changes the current directory, and assumes that the client doesn't either. Example: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories
walk
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def execle(file, *args): """execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process. """ env = args[-1] execve(file, args[:-1], env)
execle(file, *args, env) Execute the executable file with argument list args and environment env, replacing the current process.
execle
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def execlpe(file, *args): """execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process. """ env = args[-1] execvpe(file, args[:-1], env)
execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process.
execlpe
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def spawnle(mode, file, *args): """spawnle(mode, file, *args, env) -> integer Execute file with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ env = args[-1] return spawnve(mode, file, args[:-1], env)
spawnle(mode, file, *args, env) -> integer Execute file with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
spawnle
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def spawnlpe(mode, file, *args): """spawnlpe(mode, file, *args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it. """ env = args[-1] return spawnvpe(mode, file, args[:-1], env)
spawnlpe(mode, file, *args, env) -> integer Execute file (which is looked for along $PATH) with arguments from args in a subprocess with the supplied environment. If mode == P_NOWAIT return the pid of the process. If mode == P_WAIT return the process's exit code if it exits normally; otherwise return -SIG, where SIG is the signal that killed it.
spawnlpe
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def popen2(cmd, mode="t", bufsize=-1): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout) are returned.""" import warnings msg = "os.popen2 is deprecated. Use the subprocess module." warnings.warn(msg, DeprecationWarning, stacklevel=2) import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) return p.stdin, p.stdout
Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout) are returned.
popen2
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def popen3(cmd, mode="t", bufsize=-1): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout, child_stderr) are returned.""" import warnings msg = "os.popen3 is deprecated. Use the subprocess module." warnings.warn(msg, DeprecationWarning, stacklevel=2) import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) return p.stdin, p.stdout, p.stderr
Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout, child_stderr) are returned.
popen3
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def popen4(cmd, mode="t", bufsize=-1): """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout_stderr) are returned.""" import warnings msg = "os.popen4 is deprecated. Use the subprocess module." warnings.warn(msg, DeprecationWarning, stacklevel=2) import subprocess PIPE = subprocess.PIPE p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring), bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=subprocess.STDOUT, close_fds=True) return p.stdin, p.stdout
Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdin, child_stdout_stderr) are returned.
popen4
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os.py
MIT
def join(a, *p): """Join two or more pathname components, inserting sep as needed""" path = a for b in p: if isabs(b): path = b elif path == '' or path[-1:] in '/\\:': path = path + b else: path = path + '/' + b return path
Join two or more pathname components, inserting sep as needed
join
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os2emxpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os2emxpath.py
MIT
def splitunc(p): """Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have a UNC part. """ if p[1:2] == ':': return '', p # Drive letter present firstTwo = p[0:2] if firstTwo == '/' * 2 or firstTwo == '\\' * 2: # is a UNC path: # vvvvvvvvvvvvvvvvvvvv equivalent to drive letter # \\machine\mountpoint\directories... # directory ^^^^^^^^^^^^^^^ normp = normcase(p) index = normp.find('/', 2) if index == -1: ##raise RuntimeError, 'illegal UNC path: "' + p + '"' return ("", p) index = normp.find('/', index + 1) if index == -1: index = len(p) return p[:index], p[index:] return '', p
Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mount' (or similar using backslashes). unc+rest is always the input path. Paths containing drive letters never have a UNC part.
splitunc
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os2emxpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os2emxpath.py
MIT
def ismount(path): """Test whether a path is a mount point (defined as root of drive)""" unc, rest = splitunc(path) if unc: return rest in ("", "/", "\\") p = splitdrive(path)[1] return len(p) == 1 and p[0] in '/\\'
Test whether a path is a mount point (defined as root of drive)
ismount
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os2emxpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os2emxpath.py
MIT
def normpath(path): """Normalize path, eliminating double slashes, etc.""" path = path.replace('\\', '/') prefix, path = splitdrive(path) while path[:1] == '/': prefix = prefix + '/' path = path[1:] comps = path.split('/') i = 0 while i < len(comps): if comps[i] == '.': del comps[i] elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'): del comps[i-1:i+1] i = i - 1 elif comps[i] == '' and i > 0 and comps[i-1] != '': del comps[i] else: i = i + 1 # If the path is now empty, substitute '.' if not prefix and not comps: comps.append('.') return prefix + '/'.join(comps)
Normalize path, eliminating double slashes, etc.
normpath
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os2emxpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os2emxpath.py
MIT
def abspath(path): """Return the absolute version of a path""" if not isabs(path): if isinstance(path, _unicode): cwd = os.getcwdu() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path)
Return the absolute version of a path
abspath
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/os2emxpath.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/os2emxpath.py
MIT
def user_call(self, frame, argument_list): """This method is called when there is the remote possibility that we ever need to stop in this function.""" if self._wait_for_mainpyfile: return if self.stop_here(frame): print >>self.stdout, '--Call--' self.interaction(frame, None)
This method is called when there is the remote possibility that we ever need to stop in this function.
user_call
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def user_line(self, frame): """This function is called when we stop or break at this line.""" if self._wait_for_mainpyfile: if (self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno<= 0): return self._wait_for_mainpyfile = 0 if self.bp_commands(frame): self.interaction(frame, None)
This function is called when we stop or break at this line.
user_line
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def bp_commands(self,frame): """Call every command that was set for the current active breakpoint (if there is one). Returns True if the normal interaction function must be called, False otherwise.""" # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit if getattr(self, "currentbp", False) and \ self.currentbp in self.commands: currentbp = self.currentbp self.currentbp = 0 lastcmd_back = self.lastcmd self.setup(frame, None) for line in self.commands[currentbp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[currentbp]: self.print_stack_entry(self.stack[self.curindex]) if self.commands_doprompt[currentbp]: self.cmdloop() self.forget() return return 1
Call every command that was set for the current active breakpoint (if there is one). Returns True if the normal interaction function must be called, False otherwise.
bp_commands
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" if self._wait_for_mainpyfile: return frame.f_locals['__return__'] = return_value print >>self.stdout, '--Return--' self.interaction(frame, None)
This function is called when a return trap is set here.
user_return
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def user_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" if self._wait_for_mainpyfile: return exc_type, exc_value, exc_traceback = exc_info frame.f_locals['__exception__'] = exc_type, exc_value if type(exc_type) == type(''): exc_type_name = exc_type else: exc_type_name = exc_type.__name__ print >>self.stdout, exc_type_name + ':', _saferepr(exc_value) self.interaction(frame, exc_traceback)
This function is called if an exception occurs, but only if we are to stop at or just below this level.
user_exception
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def displayhook(self, obj): """Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins. """ # reproduce the behavior of the standard displayhook, not printing None if obj is not None: print repr(obj)
Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins.
displayhook
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition. """ if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition.
onecmd
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def handle_command_def(self,line): """Handles one command line during command list definition.""" cmd, arg, line = self.parseline(line) if not cmd: return if cmd == 'silent': self.commands_silent[self.commands_bnum] = True return # continue to handle other cmd def in the cmd list elif cmd == 'end': self.cmdqueue = [] return 1 # end of cmd list cmdlist = self.commands[self.commands_bnum] if arg: cmdlist.append(cmd+' '+arg) else: cmdlist.append(cmd) # Determine if we must stop try: func = getattr(self, 'do_' + cmd) except AttributeError: func = self.default # one of the resuming commands if func.func_name in self.commands_resuming: self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 return
Handles one command line during command list definition.
handle_command_def
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def do_commands(self, arg): """Defines a list of commands associated to a breakpoint. Those commands will be executed whenever the breakpoint causes the program to stop execution.""" if not arg: bnum = len(bdb.Breakpoint.bpbynumber)-1 else: try: bnum = int(arg) except: print >>self.stdout, "Usage : commands [bnum]\n ..." \ "\n end" return self.commands_bnum = bnum self.commands[bnum] = [] self.commands_doprompt[bnum] = True self.commands_silent[bnum] = False prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True try: self.cmdloop() finally: self.commands_defining = False self.prompt = prompt_back
Defines a list of commands associated to a breakpoint. Those commands will be executed whenever the breakpoint causes the program to stop execution.
do_commands
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def checkline(self, filename, lineno): """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. """ # this method should be callable before starting debugging, so default # to "no globals" if there is no current frame globs = self.curframe.f_globals if hasattr(self, 'curframe') else None line = linecache.getline(filename, lineno, globs) if not line: print >>self.stdout, 'End of file' return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): print >>self.stdout, '*** Blank or comment' return 0 return lineno
Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive.
checkline
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def do_ignore(self,arg): """arg is bp number followed by ignore count.""" args = arg.split() try: bpnum = int(args[0].strip()) except ValueError: # something went wrong print >>self.stdout, \ 'Breakpoint index %r is not a number' % args[0] return try: count = int(args[1].strip()) except: count = 0 try: bp = bdb.Breakpoint.bpbynumber[bpnum] except IndexError: print >>self.stdout, 'Breakpoint index %r is not valid' % args[0] return if bp: bp.ignore = count if count > 0: reply = 'Will ignore next ' if count > 1: reply = reply + '%d crossings' % count else: reply = reply + '1 crossing' print >>self.stdout, reply + ' of breakpoint %d.' % bpnum else: print >>self.stdout, 'Will stop next time breakpoint', print >>self.stdout, bpnum, 'is reached.'
arg is bp number followed by ignore count.
do_ignore
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def do_clear(self, arg): """Three possibilities, tried in this order: clear -> clear all breaks, ask for confirmation clear file:lineno -> clear all breaks at file:lineno clear bpno bpno ... -> clear breakpoints by number""" if not arg: try: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if reply in ('y', 'yes'): self.clear_all_breaks() return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = arg.rfind(':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except ValueError: err = "Invalid line number (%s)" % arg else: err = self.clear_break(filename, lineno) if err: print >>self.stdout, '***', err return numberlist = arg.split() for i in numberlist: try: i = int(i) except ValueError: print >>self.stdout, 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print >>self.stdout, 'No breakpoint numbered', i continue err = self.clear_bpbynumber(i) if err: print >>self.stdout, '***', err else: print >>self.stdout, 'Deleted breakpoint', i
Three possibilities, tried in this order: clear -> clear all breaks, ask for confirmation clear file:lineno -> clear all breaks at file:lineno clear bpno bpno ... -> clear breakpoints by number
do_clear
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def do_run(self, arg): """Restart program by raising an exception to be caught in the main debugger loop. If arguments were given, set them in sys.argv.""" if arg: import shlex argv0 = sys.argv[0:1] sys.argv = shlex.split(arg) sys.argv[:0] = argv0 raise Restart
Restart program by raising an exception to be caught in the main debugger loop. If arguments were given, set them in sys.argv.
do_run
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def lookupmodule(self, filename): """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. """ if os.path.isabs(filename) and os.path.exists(filename): return filename f = os.path.join(sys.path[0], filename) if os.path.exists(f) and self.canonic(f) == self.mainpyfile: return f root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None
Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name.
lookupmodule
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pdb.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pdb.py
MIT
def __init__(self, file, protocol=None): """This takes a file-like object for writing a pickle data stream. The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text mode and read back successfully. When using a protocol higher than 0, make sure the file is opened in binary mode, both when pickling and unpickling.) Protocol 1 is more efficient than protocol 0; protocol 2 is more efficient than protocol 1. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The file parameter must have a write() method that accepts a single string argument. It can thus be an open file object, a StringIO object, or any other custom object that meets this interface. """ if protocol is None: protocol = 0 if protocol < 0: protocol = HIGHEST_PROTOCOL elif not 0 <= protocol <= HIGHEST_PROTOCOL: raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) self.write = file.write self.memo = {} self.proto = int(protocol) self.bin = protocol >= 1 self.fast = 0
This takes a file-like object for writing a pickle data stream. The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2. The default protocol is 0, to be backwards compatible. (Protocol 0 is the only protocol that can be written to a file opened in text mode and read back successfully. When using a protocol higher than 0, make sure the file is opened in binary mode, both when pickling and unpickling.) Protocol 1 is more efficient than protocol 0; protocol 2 is more efficient than protocol 1. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The file parameter must have a write() method that accepts a single string argument. It can thus be an open file object, a StringIO object, or any other custom object that meets this interface.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def dump(self, obj): """Write a pickled representation of obj to the open file.""" if self.proto >= 2: self.write(PROTO + chr(self.proto)) self.save(obj) self.write(STOP)
Write a pickled representation of obj to the open file.
dump
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def memoize(self, obj): """Store an object in the memo.""" # The Pickler memo is a dictionary mapping object ids to 2-tuples # that contain the Unpickler memo key and the object being memoized. # The memo key is written to the pickle and will become # the key in the Unpickler's memo. The object is stored in the # Pickler memo so that transient objects are kept alive during # pickling. # The use of the Unpickler memo length as the memo key is just a # convention. The only requirement is that the memo values be unique. # But there appears no advantage to any other scheme, and this # scheme allows the Unpickler memo to be implemented as a plain (but # growable) array, indexed by memo key. if self.fast: return assert id(obj) not in self.memo memo_len = len(self.memo) self.write(self.put(memo_len)) self.memo[id(obj)] = memo_len, obj
Store an object in the memo.
memoize
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def _keep_alive(x, memo): """Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo itself... """ try: memo[id(memo)].append(x) except KeyError: # aha, this is the first one :-) memo[id(memo)]=[x]
Keeps a reference to the object x in the memo. Because we remember objects by their id, we have to assure that possibly temporary objects are kept alive by referencing them. We store a reference at the id of the memo, which should normally not be used unless someone tries to deepcopy the memo itself...
_keep_alive
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def whichmodule(func, funcname): """Figure out the module in which a function occurs. Search sys.modules for the module. Cache in classmap. Return a module name. If the function cannot be found, return "__main__". """ # Python functions should always get an __module__ from their globals. mod = getattr(func, "__module__", None) if mod is not None: return mod if func in classmap: return classmap[func] for name, module in sys.modules.items(): if module is None: continue # skip dummy package entries if name != '__main__' and getattr(module, funcname, None) is func: break else: name = '__main__' classmap[func] = name return name
Figure out the module in which a function occurs. Search sys.modules for the module. Cache in classmap. Return a module name. If the function cannot be found, return "__main__".
whichmodule
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def __init__(self, file): """This takes a file-like object for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. The file-like object must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return a string. Thus file-like object can be a file object opened for reading, a StringIO object, or any other custom object that meets this interface. """ self.readline = file.readline self.read = file.read self.memo = {}
This takes a file-like object for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. The file-like object must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return a string. Thus file-like object can be a file object opened for reading, a StringIO object, or any other custom object that meets this interface.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def load(self): """Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file. """ self.mark = object() # any new unique object self.stack = [] self.append = self.stack.append read = self.read dispatch = self.dispatch try: while 1: key = read(1) dispatch[key](self) except _Stop, stopinst: return stopinst.value
Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file.
load
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def encode_long(x): r"""Encode a long to a two's complement little-endian binary string. Note that 0L is a special case, returning an empty string, to save a byte in the LONG1 pickling context. >>> encode_long(0L) '' >>> encode_long(255L) '\xff\x00' >>> encode_long(32767L) '\xff\x7f' >>> encode_long(-256L) '\x00\xff' >>> encode_long(-32768L) '\x00\x80' >>> encode_long(-128L) '\x80' >>> encode_long(127L) '\x7f' >>> """ if x == 0: return '' if x > 0: ashex = hex(x) assert ashex.startswith("0x") njunkchars = 2 + ashex.endswith('L') nibbles = len(ashex) - njunkchars if nibbles & 1: # need an even # of nibbles for unhexlify ashex = "0x0" + ashex[2:] elif int(ashex[2], 16) >= 8: # "looks negative", so need a byte of sign bits ashex = "0x00" + ashex[2:] else: # Build the 256's-complement: (1L << nbytes) + x. The trick is # to find the number of bytes in linear time (although that should # really be a constant-time task). ashex = hex(-x) assert ashex.startswith("0x") njunkchars = 2 + ashex.endswith('L') nibbles = len(ashex) - njunkchars if nibbles & 1: # Extend to a full byte. nibbles += 1 nbits = nibbles * 4 x += 1L << nbits assert x > 0 ashex = hex(x) njunkchars = 2 + ashex.endswith('L') newnibbles = len(ashex) - njunkchars if newnibbles < nibbles: ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:] if int(ashex[2], 16) < 8: # "looks positive", so need a byte of sign bits ashex = "0xff" + ashex[2:] if ashex.endswith('L'): ashex = ashex[2:-1] else: ashex = ashex[2:] assert len(ashex) & 1 == 0, (x, ashex) binary = _binascii.unhexlify(ashex) return binary[::-1]
Encode a long to a two's complement little-endian binary string. Note that 0L is a special case, returning an empty string, to save a byte in the LONG1 pickling context. >>> encode_long(0L) '' >>> encode_long(255L) '\xff\x00' >>> encode_long(32767L) '\xff\x7f' >>> encode_long(-256L) '\x00\xff' >>> encode_long(-32768L) '\x00\x80' >>> encode_long(-128L) '\x80' >>> encode_long(127L) '\x7f' >>>
encode_long
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. >>> decode_long('') 0L >>> decode_long("\xff\x00") 255L >>> decode_long("\xff\x7f") 32767L >>> decode_long("\x00\xff") -256L >>> decode_long("\x00\x80") -32768L >>> decode_long("\x80") -128L >>> decode_long("\x7f") 127L """ nbytes = len(data) if nbytes == 0: return 0L ashex = _binascii.hexlify(data[::-1]) n = long(ashex, 16) # quadratic time before Python 2.3; linear now if data[-1] >= '\x80': n -= 1L << (nbytes * 8) return n
Decode a long from a two's complement little-endian binary string. >>> decode_long('') 0L >>> decode_long("\xff\x00") 255L >>> decode_long("\xff\x7f") 32767L >>> decode_long("\x00\xff") -256L >>> decode_long("\x00\x80") -32768L >>> decode_long("\x80") -128L >>> decode_long("\x7f") 127L
decode_long
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickle.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickle.py
MIT
def read_uint2(f): r""" >>> import StringIO >>> read_uint2(StringIO.StringIO('\xff\x00')) 255 >>> read_uint2(StringIO.StringIO('\xff\xff')) 65535 """ data = f.read(2) if len(data) == 2: return _unpack("<H", data)[0] raise ValueError("not enough data in stream to read uint2")
>>> import StringIO >>> read_uint2(StringIO.StringIO('\xff\x00')) 255 >>> read_uint2(StringIO.StringIO('\xff\xff')) 65535
read_uint2
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_int4(f): r""" >>> import StringIO >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00')) 255 >>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31) True """ data = f.read(4) if len(data) == 4: return _unpack("<i", data)[0] raise ValueError("not enough data in stream to read int4")
>>> import StringIO >>> read_int4(StringIO.StringIO('\xff\x00\x00\x00')) 255 >>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31) True
read_int4
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_stringnl(f, decode=True, stripquotes=True): r""" >>> import StringIO >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n")) 'abcd' >>> read_stringnl(StringIO.StringIO("\n")) Traceback (most recent call last): ... ValueError: no string quotes around '' >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False) '' >>> read_stringnl(StringIO.StringIO("''\n")) '' >>> read_stringnl(StringIO.StringIO('"abcd"')) Traceback (most recent call last): ... ValueError: no newline found when trying to read stringnl Embedded escapes are undone in the result. >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'")) 'a\n\\b\x00c\td' """ data = f.readline() if not data.endswith('\n'): raise ValueError("no newline found when trying to read stringnl") data = data[:-1] # lose the newline if stripquotes: for q in "'\"": if data.startswith(q): if not data.endswith(q): raise ValueError("strinq quote %r not found at both " "ends of %r" % (q, data)) data = data[1:-1] break else: raise ValueError("no string quotes around %r" % data) # I'm not sure when 'string_escape' was added to the std codecs; it's # crazy not to use it if it's there. if decode: data = data.decode('string_escape') return data
>>> import StringIO >>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n")) 'abcd' >>> read_stringnl(StringIO.StringIO("\n")) Traceback (most recent call last): ... ValueError: no string quotes around '' >>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False) '' >>> read_stringnl(StringIO.StringIO("''\n")) '' >>> read_stringnl(StringIO.StringIO('"abcd"')) Traceback (most recent call last): ... ValueError: no newline found when trying to read stringnl Embedded escapes are undone in the result. >>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'")) 'a\n\\b\x00c\td'
read_stringnl
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_string4(f): r""" >>> import StringIO >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc")) '' >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef")) 'abc' >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef")) Traceback (most recent call last): ... ValueError: expected 50331648 bytes in a string4, but only 6 remain """ n = read_int4(f) if n < 0: raise ValueError("string4 byte count < 0: %d" % n) data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a string4, but only %d remain" % (n, len(data)))
>>> import StringIO >>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc")) '' >>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef")) 'abc' >>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef")) Traceback (most recent call last): ... ValueError: expected 50331648 bytes in a string4, but only 6 remain
read_string4
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_string1(f): r""" >>> import StringIO >>> read_string1(StringIO.StringIO("\x00")) '' >>> read_string1(StringIO.StringIO("\x03abcdef")) 'abc' """ n = read_uint1(f) assert n >= 0 data = f.read(n) if len(data) == n: return data raise ValueError("expected %d bytes in a string1, but only %d remain" % (n, len(data)))
>>> import StringIO >>> read_string1(StringIO.StringIO("\x00")) '' >>> read_string1(StringIO.StringIO("\x03abcdef")) 'abc'
read_string1
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_unicodestringnl(f): r""" >>> import StringIO >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk")) u'abc\uabcd' """ data = f.readline() if not data.endswith('\n'): raise ValueError("no newline found when trying to read " "unicodestringnl") data = data[:-1] # lose the newline return unicode(data, 'raw-unicode-escape')
>>> import StringIO >>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk")) u'abc\uabcd'
read_unicodestringnl
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_unicodestring4(f): r""" >>> import StringIO >>> s = u'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc 'abcd\xea\xaf\x8d' >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk')) >>> s == t True >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring4, but only 6 remain """ n = read_int4(f) if n < 0: raise ValueError("unicodestring4 byte count < 0: %d" % n) data = f.read(n) if len(data) == n: return unicode(data, 'utf-8') raise ValueError("expected %d bytes in a unicodestring4, but only %d " "remain" % (n, len(data)))
>>> import StringIO >>> s = u'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc 'abcd\xea\xaf\x8d' >>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length >>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk')) >>> s == t True >>> read_unicodestring4(StringIO.StringIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
read_unicodestring4
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_decimalnl_short(f): r""" >>> import StringIO >>> read_decimalnl_short(StringIO.StringIO("1234\n56")) 1234 >>> read_decimalnl_short(StringIO.StringIO("1234L\n56")) Traceback (most recent call last): ... ValueError: trailing 'L' not allowed in '1234L' """ s = read_stringnl(f, decode=False, stripquotes=False) if s.endswith("L"): raise ValueError("trailing 'L' not allowed in %r" % s) # It's not necessarily true that the result fits in a Python short int: # the pickle may have been written on a 64-bit box. There's also a hack # for True and False here. if s == "00": return False elif s == "01": return True try: return int(s) except OverflowError: return long(s)
>>> import StringIO >>> read_decimalnl_short(StringIO.StringIO("1234\n56")) 1234 >>> read_decimalnl_short(StringIO.StringIO("1234L\n56")) Traceback (most recent call last): ... ValueError: trailing 'L' not allowed in '1234L'
read_decimalnl_short
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_decimalnl_long(f): r""" >>> import StringIO >>> read_decimalnl_long(StringIO.StringIO("1234\n56")) Traceback (most recent call last): ... ValueError: trailing 'L' required in '1234' Someday the trailing 'L' will probably go away from this output. >>> read_decimalnl_long(StringIO.StringIO("1234L\n56")) 1234L >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6")) 123456789012345678901234L """ s = read_stringnl(f, decode=False, stripquotes=False) if not s.endswith("L"): raise ValueError("trailing 'L' required in %r" % s) return long(s)
>>> import StringIO >>> read_decimalnl_long(StringIO.StringIO("1234\n56")) Traceback (most recent call last): ... ValueError: trailing 'L' required in '1234' Someday the trailing 'L' will probably go away from this output. >>> read_decimalnl_long(StringIO.StringIO("1234L\n56")) 1234L >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6")) 123456789012345678901234L
read_decimalnl_long
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_float8(f): r""" >>> import StringIO, struct >>> raw = struct.pack(">d", -1.25) >>> raw '\xbf\xf4\x00\x00\x00\x00\x00\x00' >>> read_float8(StringIO.StringIO(raw + "\n")) -1.25 """ data = f.read(8) if len(data) == 8: return _unpack(">d", data)[0] raise ValueError("not enough data in stream to read float8")
>>> import StringIO, struct >>> raw = struct.pack(">d", -1.25) >>> raw '\xbf\xf4\x00\x00\x00\x00\x00\x00' >>> read_float8(StringIO.StringIO(raw + "\n")) -1.25
read_float8
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_long1(f): r""" >>> import StringIO >>> read_long1(StringIO.StringIO("\x00")) 0L >>> read_long1(StringIO.StringIO("\x02\xff\x00")) 255L >>> read_long1(StringIO.StringIO("\x02\xff\x7f")) 32767L >>> read_long1(StringIO.StringIO("\x02\x00\xff")) -256L >>> read_long1(StringIO.StringIO("\x02\x00\x80")) -32768L """ n = read_uint1(f) data = f.read(n) if len(data) != n: raise ValueError("not enough data in stream to read long1") return decode_long(data)
>>> import StringIO >>> read_long1(StringIO.StringIO("\x00")) 0L >>> read_long1(StringIO.StringIO("\x02\xff\x00")) 255L >>> read_long1(StringIO.StringIO("\x02\xff\x7f")) 32767L >>> read_long1(StringIO.StringIO("\x02\x00\xff")) -256L >>> read_long1(StringIO.StringIO("\x02\x00\x80")) -32768L
read_long1
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def read_long4(f): r""" >>> import StringIO >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00")) 255L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f")) 32767L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff")) -256L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80")) -32768L >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00")) 0L """ n = read_int4(f) if n < 0: raise ValueError("long4 byte count < 0: %d" % n) data = f.read(n) if len(data) != n: raise ValueError("not enough data in stream to read long4") return decode_long(data)
>>> import StringIO >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00")) 255L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f")) 32767L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff")) -256L >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80")) -32768L >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00")) 0L
read_long4
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def genops(pickle): """Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a string object, it's wrapped in a StringIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None. """ import cStringIO as StringIO if isinstance(pickle, str): pickle = StringIO.StringIO(pickle) if hasattr(pickle, "tell"): getpos = pickle.tell else: getpos = lambda: None while True: pos = getpos() code = pickle.read(1) opcode = code2op.get(code) if opcode is None: if code == "": raise ValueError("pickle exhausted before seeing STOP") else: raise ValueError("at position %s, opcode %r unknown" % ( pos is None and "<unknown>" or pos, code)) if opcode.arg is None: arg = None else: arg = opcode.arg.reader(pickle) yield opcode, arg, pos if code == '.': assert opcode.name == 'STOP' break
Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a string object, it's wrapped in a StringIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None.
genops
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def optimize(p): 'Optimize a pickle string by removing unused PUT opcodes' gets = set() # set of args used by a GET opcode puts = [] # (arg, startpos, stoppos) for the PUT opcodes prevpos = None # set to pos if previous opcode was a PUT for opcode, arg, pos in genops(p): if prevpos is not None: puts.append((prevarg, prevpos, pos)) prevpos = None if 'PUT' in opcode.name: prevarg, prevpos = arg, pos elif 'GET' in opcode.name: gets.add(arg) # Copy the pickle string except for PUTS without a corresponding GET s = [] i = 0 for arg, start, stop in puts: j = stop if (arg in gets) else start s.append(p[i:j]) i = stop s.append(p[i:]) return ''.join(s)
Optimize a pickle string by removing unused PUT opcodes
optimize
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def dis(pickle, out=None, memo=None, indentlevel=4): """Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined. """ # Most of the hair here is for sanity checks, but most of it is needed # anyway to detect when a protocol 0 POP takes a MARK off the stack # (which in turn is needed to indent MARK blocks correctly). stack = [] # crude emulation of unpickler stack if memo is None: memo = {} # crude emulation of unpickler memo maxproto = -1 # max protocol number seen markstack = [] # bytecode positions of MARK opcodes indentchunk = ' ' * indentlevel errormsg = None for opcode, arg, pos in genops(pickle): if pos is not None: print >> out, "%5d:" % pos, line = "%-4s %s%s" % (repr(opcode.code)[1:-1], indentchunk * len(markstack), opcode.name) maxproto = max(maxproto, opcode.proto) before = opcode.stack_before # don't mutate after = opcode.stack_after # don't mutate numtopop = len(before) # See whether a MARK should be popped. markmsg = None if markobject in before or (opcode.name == "POP" and stack and stack[-1] is markobject): assert markobject not in after if __debug__: if markobject in before: assert before[-1] is stackslice if markstack: markpos = markstack.pop() if markpos is None: markmsg = "(MARK at unknown opcode offset)" else: markmsg = "(MARK at %d)" % markpos # Pop everything at and after the topmost markobject. while stack[-1] is not markobject: stack.pop() stack.pop() # Stop later code from popping too much. try: numtopop = before.index(markobject) except ValueError: assert opcode.name == "POP" numtopop = 0 else: errormsg = markmsg = "no MARK exists on stack" # Check for correct memo usage. if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"): assert arg is not None if arg in memo: errormsg = "memo key %r already defined" % arg elif not stack: errormsg = "stack is empty -- can't store into memo" elif stack[-1] is markobject: errormsg = "can't store markobject in the memo" else: memo[arg] = stack[-1] elif opcode.name in ("GET", "BINGET", "LONG_BINGET"): if arg in memo: assert len(after) == 1 after = [memo[arg]] # for better stack emulation else: errormsg = "memo key %r has never been stored into" % arg if arg is not None or markmsg: # make a mild effort to align arguments line += ' ' * (10 - len(opcode.name)) if arg is not None: line += ' ' + repr(arg) if markmsg: line += ' ' + markmsg print >> out, line if errormsg: # Note that we delayed complaining until the offending opcode # was printed. raise ValueError(errormsg) # Emulate the stack effects. if len(stack) < numtopop: raise ValueError("tries to pop %d items from stack with " "only %d items" % (numtopop, len(stack))) if numtopop: del stack[-numtopop:] if markobject in after: assert markobject not in before markstack.append(pos) stack.extend(after) print >> out, "highest protocol among opcodes =", maxproto if stack: raise ValueError("stack not empty after STOP: %r" % stack)
Produce a symbolic disassembly of a pickle. 'pickle' is a file-like object, or string, containing a (at least one) pickle. The pickle is disassembled from the current position, through the first STOP opcode encountered. Optional arg 'out' is a file-like object to which the disassembly is printed. It defaults to sys.stdout. Optional arg 'memo' is a Python dict, used as the pickle's memo. It may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes. Passing the same memo object to another dis() call then allows disassembly to proceed across multiple pickles that were all created by the same pickler with the same memo. Ordinarily you don't need to worry about this. Optional arg indentlevel is the number of blanks by which to indent a new MARK level. It defaults to 4. In addition to printing the disassembly, some sanity checks are made: + All embedded opcode arguments "make sense". + Explicit and implicit pop operations have enough items on the stack. + When an opcode implicitly refers to a markobject, a markobject is actually on the stack. + A memo entry isn't referenced before it's defined. + The markobject isn't stored in the memo. + A memo entry isn't redefined.
dis
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pickletools.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pickletools.py
MIT
def clone(self): """t.clone() returns a new pipeline template with identical initial state as the current one.""" t = Template() t.steps = self.steps[:] t.debugging = self.debugging return t
t.clone() returns a new pipeline template with identical initial state as the current one.
clone
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pipes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pipes.py
MIT
def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.append: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.append: bad kind %r' % (kind,) if kind == SOURCE: raise ValueError, \ 'Template.append: SOURCE can only be prepended' if self.steps and self.steps[-1][1] == SINK: raise ValueError, \ 'Template.append: already ends with SINK' if kind[0] == 'f' and not re.search(r'\$IN\b', cmd): raise ValueError, \ 'Template.append: missing $IN in cmd' if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd): raise ValueError, \ 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
t.append(cmd, kind) adds a new step at the end.
append
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pipes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pipes.py
MIT
def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.prepend: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.prepend: bad kind %r' % (kind,) if kind == SINK: raise ValueError, \ 'Template.prepend: SINK can only be appended' if self.steps and self.steps[0][1] == SOURCE: raise ValueError, \ 'Template.prepend: already begins with SOURCE' if kind[0] == 'f' and not re.search(r'\$IN\b', cmd): raise ValueError, \ 'Template.prepend: missing $IN in cmd' if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd): raise ValueError, \ 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
t.prepend(cmd, kind) adds a new step at the front.
prepend
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pipes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pipes.py
MIT
def open(self, file, rw): """t.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.""" if rw == 'r': return self.open_r(file) if rw == 'w': return self.open_w(file) raise ValueError, \ 'Template.open: rw must be \'r\' or \'w\', not %r' % (rw,)
t.open(file, rw) returns a pipe or file object open for reading or writing; the file is the other end of the pipeline.
open
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pipes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pipes.py
MIT
def open_r(self, file): """t.open_r(file) and t.open_w(file) implement t.open(file, 'r') and t.open(file, 'w') respectively.""" if not self.steps: return open(file, 'r') if self.steps[-1][1] == SINK: raise ValueError, \ 'Template.open_r: pipeline ends width SINK' cmd = self.makepipeline(file, '') return os.popen(cmd, 'r')
t.open_r(file) and t.open_w(file) implement t.open(file, 'r') and t.open(file, 'w') respectively.
open_r
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pipes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pipes.py
MIT
def quote(file): """Return a shell-escaped version of the file string.""" for c in file: if c not in _safechars: break else: if not file: return "''" return file # use single quotes, and put single quotes into double quotes # the string $'b is then quoted as '$'"'"'b' return "'" + file.replace("'", "'\"'\"'") + "'"
Return a shell-escaped version of the file string.
quote
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pipes.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pipes.py
MIT
def simplegeneric(func): """Make a trivial single-dispatch generic function""" registry = {} def wrapper(*args, **kw): ob = args[0] try: cls = ob.__class__ except AttributeError: cls = type(ob) try: mro = cls.__mro__ except AttributeError: try: class cls(cls, object): pass mro = cls.__mro__[1:] except TypeError: mro = object, # must be an ExtensionClass or some such :( for t in mro: if t in registry: return registry[t](*args, **kw) else: return func(*args, **kw) try: wrapper.__name__ = func.__name__ except (TypeError, AttributeError): pass # Python 2.3 doesn't allow functions to be renamed def register(typ, func=None): if func is None: return lambda f: register(typ, f) registry[typ] = func return func wrapper.__dict__ = func.__dict__ wrapper.__doc__ = func.__doc__ wrapper.register = register return wrapper
Make a trivial single-dispatch generic function
simplegeneric
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pkgutil.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pkgutil.py
MIT
def walk_packages(path=None, prefix='', onerror=None): """Yields (module_loader, name, ispkg) for all modules recursively on path, or, if path is None, all accessible modules. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output. Note that this function must import all *packages* (NOT all modules!) on the given path, in order to access the __path__ attribute to find submodules. 'onerror' is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package. If no onerror function is supplied, ImportErrors are caught and ignored, while all other exceptions are propagated, terminating the search. Examples: # list all modules python can access walk_packages() # list all submodules of ctypes walk_packages(ctypes.__path__, ctypes.__name__+'.') """ def seen(p, m={}): if p in m: return True m[p] = True for importer, name, ispkg in iter_modules(path, prefix): yield importer, name, ispkg if ispkg: try: __import__(name) except ImportError: if onerror is not None: onerror(name) except Exception: if onerror is not None: onerror(name) else: raise else: path = getattr(sys.modules[name], '__path__', None) or [] # don't traverse path items we've seen before path = [p for p in path if not seen(p)] for item in walk_packages(path, name+'.', onerror): yield item
Yields (module_loader, name, ispkg) for all modules recursively on path, or, if path is None, all accessible modules. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output. Note that this function must import all *packages* (NOT all modules!) on the given path, in order to access the __path__ attribute to find submodules. 'onerror' is a function which gets called with one argument (the name of the package which was being imported) if any exception occurs while trying to import a package. If no onerror function is supplied, ImportErrors are caught and ignored, while all other exceptions are propagated, terminating the search. Examples: # list all modules python can access walk_packages() # list all submodules of ctypes walk_packages(ctypes.__path__, ctypes.__name__+'.')
walk_packages
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pkgutil.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pkgutil.py
MIT
def iter_modules(path=None, prefix=''): """Yields (module_loader, name, ispkg) for all submodules on path, or, if path is None, all top-level modules on sys.path. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output. """ if path is None: importers = iter_importers() else: importers = map(get_importer, path) yielded = {} for i in importers: for name, ispkg in iter_importer_modules(i, prefix): if name not in yielded: yielded[name] = 1 yield i, name, ispkg
Yields (module_loader, name, ispkg) for all submodules on path, or, if path is None, all top-level modules on sys.path. 'path' should be either None or a list of paths to look for modules in. 'prefix' is a string to output on the front of every module name on output.
iter_modules
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pkgutil.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pkgutil.py
MIT
def get_importer(path_item): """Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary. """ try: importer = sys.path_importer_cache[path_item] except KeyError: for path_hook in sys.path_hooks: try: importer = path_hook(path_item) break except ImportError: pass else: importer = None sys.path_importer_cache.setdefault(path_item, importer) if importer is None: try: importer = ImpImporter(path_item) except ImportError: importer = None return importer
Retrieve a PEP 302 importer for the given path item The returned importer is cached in sys.path_importer_cache if it was newly created by a path hook. If there is no importer, a wrapper around the basic import machinery is returned. This wrapper is never inserted into the importer cache (None is inserted instead). The cache (or part of it) can be cleared manually if a rescan of sys.path_hooks is necessary.
get_importer
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pkgutil.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pkgutil.py
MIT
def iter_importers(fullname=""): """Yield PEP 302 importers for the given module name If fullname contains a '.', the importers will be for the package containing fullname, otherwise they will be importers for sys.meta_path, sys.path, and Python's "classic" import machinery, in that order. If the named module is in a package, that package is imported as a side effect of invoking this function. Non PEP 302 mechanisms (e.g. the Windows registry) used by the standard import machinery to find files in alternative locations are partially supported, but are searched AFTER sys.path. Normally, these locations are searched BEFORE sys.path, preventing sys.path entries from shadowing them. For this to cause a visible difference in behaviour, there must be a module or package name that is accessible via both sys.path and one of the non PEP 302 file system mechanisms. In this case, the emulation will find the former version, while the builtin import mechanism will find the latter. Items of the following types can be affected by this discrepancy: imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY """ if fullname.startswith('.'): raise ImportError("Relative module names not supported") if '.' in fullname: # Get the containing package's __path__ pkg = '.'.join(fullname.split('.')[:-1]) if pkg not in sys.modules: __import__(pkg) path = getattr(sys.modules[pkg], '__path__', None) or [] else: for importer in sys.meta_path: yield importer path = sys.path for item in path: yield get_importer(item) if '.' not in fullname: yield ImpImporter()
Yield PEP 302 importers for the given module name If fullname contains a '.', the importers will be for the package containing fullname, otherwise they will be importers for sys.meta_path, sys.path, and Python's "classic" import machinery, in that order. If the named module is in a package, that package is imported as a side effect of invoking this function. Non PEP 302 mechanisms (e.g. the Windows registry) used by the standard import machinery to find files in alternative locations are partially supported, but are searched AFTER sys.path. Normally, these locations are searched BEFORE sys.path, preventing sys.path entries from shadowing them. For this to cause a visible difference in behaviour, there must be a module or package name that is accessible via both sys.path and one of the non PEP 302 file system mechanisms. In this case, the emulation will find the former version, while the builtin import mechanism will find the latter. Items of the following types can be affected by this discrepancy: imp.C_EXTENSION, imp.PY_SOURCE, imp.PY_COMPILED, imp.PKG_DIRECTORY
iter_importers
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pkgutil.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pkgutil.py
MIT
def extend_path(path, name): """Extend a package's path. Intended use is to place the following code in a package's __init__.py: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) This will add to the package's __path__ all subdirectories of directories on sys.path named after the package. This is useful if one wants to distribute different parts of a single logical package as multiple directories. It also looks for *.pkg files beginning where * matches the name argument. This feature is similar to *.pth files (see site.py), except that it doesn't special-case lines starting with 'import'. A *.pkg file is trusted at face value: apart from checking for duplicates, all entries found in a *.pkg file are added to the path, regardless of whether they are exist the filesystem. (This is a feature.) If the input path is not a list (as is the case for frozen packages) it is returned unchanged. The input path is not modified; an extended copy is returned. Items are only appended to the copy at the end. It is assumed that sys.path is a sequence. Items of sys.path that are not (unicode or 8-bit) strings referring to existing directories are ignored. Unicode items of sys.path that cause errors when used as filenames may cause this function to raise an exception (in line with os.path.isdir() behavior). """ if not isinstance(path, list): # This could happen e.g. when this is called from inside a # frozen package. Return the path unchanged in that case. return path pname = os.path.join(*name.split('.')) # Reconstitute as relative path # Just in case os.extsep != '.' sname = os.extsep.join(name.split('.')) sname_pkg = sname + os.extsep + "pkg" init_py = "__init__" + os.extsep + "py" path = path[:] # Start with a copy of the existing path for dir in sys.path: if not isinstance(dir, basestring) or not os.path.isdir(dir): continue subdir = os.path.join(dir, pname) # XXX This may still add duplicate entries to path on # case-insensitive filesystems initfile = os.path.join(subdir, init_py) if subdir not in path and os.path.isfile(initfile): path.append(subdir) # XXX Is this the right thing for subpackages like zope.app? # It looks for a file named "zope.app.pkg" pkgfile = os.path.join(dir, sname_pkg) if os.path.isfile(pkgfile): try: f = open(pkgfile) except IOError, msg: sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg)) else: for line in f: line = line.rstrip('\n') if not line or line.startswith('#'): continue path.append(line) # Don't check for existence! f.close() return path
Extend a package's path. Intended use is to place the following code in a package's __init__.py: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) This will add to the package's __path__ all subdirectories of directories on sys.path named after the package. This is useful if one wants to distribute different parts of a single logical package as multiple directories. It also looks for *.pkg files beginning where * matches the name argument. This feature is similar to *.pth files (see site.py), except that it doesn't special-case lines starting with 'import'. A *.pkg file is trusted at face value: apart from checking for duplicates, all entries found in a *.pkg file are added to the path, regardless of whether they are exist the filesystem. (This is a feature.) If the input path is not a list (as is the case for frozen packages) it is returned unchanged. The input path is not modified; an extended copy is returned. Items are only appended to the copy at the end. It is assumed that sys.path is a sequence. Items of sys.path that are not (unicode or 8-bit) strings referring to existing directories are ignored. Unicode items of sys.path that cause errors when used as filenames may cause this function to raise an exception (in line with os.path.isdir() behavior).
extend_path
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pkgutil.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pkgutil.py
MIT
def get_data(package, resource): """Get a resource from a package. This is a wrapper round the PEP 302 loader get_data API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using '/' as the path separator. The parent directory name '..' is not allowed, and nor is a rooted name (starting with a '/'). The function returns a binary string, which is the contents of the specified resource. For packages located in the filesystem, which have already been imported, this is the rough equivalent of d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() If the package cannot be located or loaded, or it uses a PEP 302 loader which does not support get_data(), then None is returned. """ loader = get_loader(package) if loader is None or not hasattr(loader, 'get_data'): return None mod = sys.modules.get(package) or loader.load_module(package) if mod is None or not hasattr(mod, '__file__'): return None # Modify the resource name to be compatible with the loader.get_data # signature - an os.path format "filename" starting with the dirname of # the package's __file__ parts = resource.split('/') parts.insert(0, os.path.dirname(mod.__file__)) resource_name = os.path.join(*parts) return loader.get_data(resource_name)
Get a resource from a package. This is a wrapper round the PEP 302 loader get_data API. The package argument should be the name of a package, in standard module format (foo.bar). The resource argument should be in the form of a relative filename, using '/' as the path separator. The parent directory name '..' is not allowed, and nor is a rooted name (starting with a '/'). The function returns a binary string, which is the contents of the specified resource. For packages located in the filesystem, which have already been imported, this is the rough equivalent of d = os.path.dirname(sys.modules[package].__file__) data = open(os.path.join(d, resource), 'rb').read() If the package cannot be located or loaded, or it uses a PEP 302 loader which does not support get_data(), then None is returned.
get_data
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/pkgutil.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/pkgutil.py
MIT
def libc_ver(executable=sys.executable,lib='',version='', chunksize=2048): """ Tries to determine the libc version that the file executable (which defaults to the Python interpreter) is linked against. Returns a tuple of strings (lib,version) which default to the given parameters in case the lookup fails. Note that the function has intimate knowledge of how different libc versions add symbols to the executable and thus is probably only useable for executables compiled using gcc. The file is read and scanned in chunks of chunksize bytes. """ if hasattr(os.path, 'realpath'): # Python 2.2 introduced os.path.realpath(); it is used # here to work around problems with Cygwin not being # able to open symlinks for reading executable = os.path.realpath(executable) f = open(executable,'rb') binary = f.read(chunksize) pos = 0 while 1: m = _libc_search.search(binary,pos) if not m: binary = f.read(chunksize) if not binary: break pos = 0 continue libcinit,glibc,glibcversion,so,threads,soversion = m.groups() if libcinit and not lib: lib = 'libc' elif glibc: if lib != 'glibc': lib = 'glibc' version = glibcversion elif glibcversion > version: version = glibcversion elif so: if lib != 'glibc': lib = 'libc' if soversion and soversion > version: version = soversion if threads and version[-len(threads):] != threads: version = version + threads pos = m.end() f.close() return lib,version
Tries to determine the libc version that the file executable (which defaults to the Python interpreter) is linked against. Returns a tuple of strings (lib,version) which default to the given parameters in case the lookup fails. Note that the function has intimate knowledge of how different libc versions add symbols to the executable and thus is probably only useable for executables compiled using gcc. The file is read and scanned in chunks of chunksize bytes.
libc_ver
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _dist_try_harder(distname,version,id): """ Tries some special tricks to get the distribution information in case the default method fails. Currently supports older SuSE Linux, Caldera OpenLinux and Slackware Linux distributions. """ if os.path.exists('/var/adm/inst-log/info'): # SuSE Linux stores distribution information in that file info = open('/var/adm/inst-log/info').readlines() distname = 'SuSE' for line in info: tv = string.split(line) if len(tv) == 2: tag,value = tv else: continue if tag == 'MIN_DIST_VERSION': version = string.strip(value) elif tag == 'DIST_IDENT': values = string.split(value,'-') id = values[2] return distname,version,id if os.path.exists('/etc/.installed'): # Caldera OpenLinux has some infos in that file (thanks to Colin Kong) info = open('/etc/.installed').readlines() for line in info: pkg = string.split(line,'-') if len(pkg) >= 2 and pkg[0] == 'OpenLinux': # XXX does Caldera support non Intel platforms ? If yes, # where can we find the needed id ? return 'OpenLinux',pkg[1],id if os.path.isdir('/usr/lib/setup'): # Check for slackware version tag file (thanks to Greg Andruk) verfiles = os.listdir('/usr/lib/setup') for n in range(len(verfiles)-1, -1, -1): if verfiles[n][:14] != 'slack-version-': del verfiles[n] if verfiles: verfiles.sort() distname = 'slackware' version = verfiles[-1][14:] return distname,version,id return distname,version,id
Tries some special tricks to get the distribution information in case the default method fails. Currently supports older SuSE Linux, Caldera OpenLinux and Slackware Linux distributions.
_dist_try_harder
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def linux_distribution(distname='', version='', id='', supported_dists=_supported_dists, full_distribution_name=1): """ Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. supported_dists may be given to define the set of Linux distributions to look for. It defaults to a list of currently supported Linux distributions identified by their release file name. If full_distribution_name is true (default), the full distribution read from the OS is returned. Otherwise the short name taken from supported_dists is used. Returns a tuple (distname,version,id) which default to the args given as parameters. """ try: etc = os.listdir('/etc') except os.error: # Probably not a Unix system return distname,version,id etc.sort() for file in etc: m = _release_filename.match(file) if m is not None: _distname,dummy = m.groups() if _distname in supported_dists: distname = _distname break else: return _dist_try_harder(distname,version,id) # Read the first line f = open('/etc/'+file, 'r') firstline = f.readline() f.close() _distname, _version, _id = _parse_release_file(firstline) if _distname and full_distribution_name: distname = _distname if _version: version = _version if _id: id = _id return distname, version, id
Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. supported_dists may be given to define the set of Linux distributions to look for. It defaults to a list of currently supported Linux distributions identified by their release file name. If full_distribution_name is true (default), the full distribution read from the OS is returned. Otherwise the short name taken from supported_dists is used. Returns a tuple (distname,version,id) which default to the args given as parameters.
linux_distribution
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def dist(distname='',version='',id='', supported_dists=_supported_dists): """ Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. Returns a tuple (distname,version,id) which default to the args given as parameters. """ return linux_distribution(distname, version, id, supported_dists=supported_dists, full_distribution_name=0)
Tries to determine the name of the Linux OS distribution name. The function first looks for a distribution release file in /etc and then reverts to _dist_try_harder() in case no suitable files are found. Returns a tuple (distname,version,id) which default to the args given as parameters.
dist
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
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 = string.split(version,'.') if build: l.append(build) try: ints = map(int,l) except ValueError: strings = l else: strings = map(str,ints) version = string.join(strings[:3],'.') return version
Normalize the version and build strings and return a single version string using the format major.minor.build (or patchlevel).
_norm_version
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _syscmd_ver(system='', release='', version='', supported_platforms=('win32','win16','dos','os2')): """ Tries to figure out the OS version used and returns a tuple (system,release,version). It uses the "ver" shell command for this which is known to exists on Windows, DOS and OS/2. XXX Others too ? In case this fails, the given parameters are used as defaults. """ if sys.platform not in supported_platforms: return system,release,version # Try some common cmd strings for cmd in ('ver','command /c ver','cmd /c ver'): try: pipe = popen(cmd) info = pipe.read() if pipe.close(): raise os.error,'command failed' # XXX How can I suppress shell errors from being written # to stderr ? except os.error,why: #print 'Command %s failed: %s' % (cmd,why) continue except IOError,why: #print 'Command %s failed: %s' % (cmd,why) continue else: break else: return system,release,version # Parse the output info = string.strip(info) m = _ver_output.match(info) if m is not None: system,release,version = m.groups() # Strip trailing dots from version and release if release[-1] == '.': release = release[:-1] if version[-1] == '.': version = version[:-1] # Normalize the version and build strings (eliminating additional # zeros) version = _norm_version(version) return system,release,version
Tries to figure out the OS version used and returns a tuple (system,release,version). It uses the "ver" shell command for this which is known to exists on Windows, DOS and OS/2. XXX Others too ? In case this fails, the given parameters are used as defaults.
_syscmd_ver
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _mac_ver_gestalt(): """ Thanks to Mark R. Levinson for mailing documentation links and code examples for this function. Documentation for the gestalt() API is available online at: http://www.rgaros.nl/gestalt/ """ # Check whether the version info module is available try: import gestalt import MacOS except ImportError: return None # Get the infos sysv,sysa = _mac_ver_lookup(('sysv','sysa')) # Decode the infos if sysv: major = (sysv & 0xFF00) >> 8 minor = (sysv & 0x00F0) >> 4 patch = (sysv & 0x000F) if (major, minor) >= (10, 4): # the 'sysv' gestald cannot return patchlevels # higher than 9. Apple introduced 3 new # gestalt codes in 10.4 to deal with this # issue (needed because patch levels can # run higher than 9, such as 10.4.11) major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3')) release = '%i.%i.%i' %(major, minor, patch) else: release = '%s.%i.%i' % (_bcd2str(major),minor,patch) if sysa: machine = {0x1: '68k', 0x2: 'PowerPC', 0xa: 'i386'}.get(sysa,'') versioninfo=('', '', '') return release,versioninfo,machine
Thanks to Mark R. Levinson for mailing documentation links and code examples for this function. Documentation for the gestalt() API is available online at: http://www.rgaros.nl/gestalt/
_mac_ver_gestalt
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
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
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.
mac_ver
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')): """ Version interface for Jython. Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being a tuple (vm_name,vm_release,vm_vendor) and osinfo being a tuple (os_name,os_version,os_arch). Values which cannot be determined are set to the defaults given as parameters (which all default to ''). """ # Import the needed APIs try: import java.lang except ImportError: return release,vendor,vminfo,osinfo vendor = _java_getprop('java.vendor', vendor) release = _java_getprop('java.version', release) vm_name, vm_release, vm_vendor = vminfo vm_name = _java_getprop('java.vm.name', vm_name) vm_vendor = _java_getprop('java.vm.vendor', vm_vendor) vm_release = _java_getprop('java.vm.version', vm_release) vminfo = vm_name, vm_release, vm_vendor os_name, os_version, os_arch = osinfo os_arch = _java_getprop('java.os.arch', os_arch) os_name = _java_getprop('java.os.name', os_name) os_version = _java_getprop('java.os.version', os_version) osinfo = os_name, os_version, os_arch return release, vendor, vminfo, osinfo
Version interface for Jython. Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being a tuple (vm_name,vm_release,vm_vendor) and osinfo being a tuple (os_name,os_version,os_arch). Values which cannot be determined are set to the defaults given as parameters (which all default to '').
java_ver
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def system_alias(system,release,version): """ Returns (system,release,version) aliased to common marketing names used for some systems. It also does some reordering of the information in some cases where it would otherwise cause confusion. """ if system == 'Rhapsody': # Apple's BSD derivative # XXX How can we determine the marketing release number ? return 'MacOS X Server',system+release,version elif system == 'SunOS': # Sun's OS if release < '5': # These releases use the old name SunOS return system,release,version # Modify release (marketing release = SunOS release - 3) l = string.split(release,'.') if l: try: major = int(l[0]) except ValueError: pass else: major = major - 3 l[0] = str(major) release = string.join(l,'.') if release < '6': system = 'Solaris' else: # XXX Whatever the new SunOS marketing name is... system = 'Solaris' elif system == 'IRIX64': # IRIX reports IRIX64 on platforms with 64-bit support; yet it # is really a version and not a different platform, since 32-bit # apps are also supported.. system = 'IRIX' if version: version = version + ' (64bit)' else: version = '64bit' elif system in ('win32','win16'): # In case one of the other tricks system = 'Windows' return system,release,version
Returns (system,release,version) aliased to common marketing names used for some systems. It also does some reordering of the information in some cases where it would otherwise cause confusion.
system_alias
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _platform(*args): """ Helper to format the platform string in a filename compatible format e.g. "system-version-machine". """ # Format the platform string platform = string.join( map(string.strip, filter(len, args)), '-') # Cleanup some possible filename obstacles... replace = string.replace platform = replace(platform,' ','_') platform = replace(platform,'/','-') platform = replace(platform,'\\','-') platform = replace(platform,':','-') platform = replace(platform,';','-') platform = replace(platform,'"','-') platform = replace(platform,'(','-') platform = replace(platform,')','-') # No need to report 'unknown' information... platform = replace(platform,'unknown','') # Fold '--'s and remove trailing '-' while 1: cleaned = replace(platform,'--','-') if cleaned == platform: break platform = cleaned while platform[-1] == '-': platform = platform[:-1] return platform
Helper to format the platform string in a filename compatible format e.g. "system-version-machine".
_platform
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _node(default=''): """ Helper to determine the node name of this machine. """ try: import socket except ImportError: # No sockets... return default try: return socket.gethostname() except socket.error: # Still not working... return default
Helper to determine the node name of this machine.
_node
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _follow_symlinks(filepath): """ In case filepath is a symlink, follow it until a real file is reached. """ filepath = _abspath(filepath) while os.path.islink(filepath): filepath = os.path.normpath( os.path.join(os.path.dirname(filepath),os.readlink(filepath))) return filepath
In case filepath is a symlink, follow it until a real file is reached.
_follow_symlinks
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _syscmd_uname(option,default=''): """ Interface to the system's uname command. """ if sys.platform in ('dos','win32','win16','os2'): # XXX Others too ? return default try: f = os.popen('uname %s 2> %s' % (option, DEV_NULL)) except (AttributeError,os.error): return default output = string.strip(f.read()) rc = f.close() if not output or rc: return default else: return output
Interface to the system's uname command.
_syscmd_uname
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def architecture(executable=sys.executable,bits='',linkage=''): """ Queries the given executable (defaults to the Python interpreter binary) for various architecture information. Returns a tuple (bits,linkage) which contains information about the bit architecture and the linkage format used for the executable. Both values are returned as strings. Values that cannot be determined are returned as given by the parameter presets. If bits is given as '', the sizeof(pointer) (or sizeof(long) on Python version < 1.5.2) is used as indicator for the supported pointer size. The function relies on the system's "file" command to do the actual work. This is available on most if not all Unix platforms. On some non-Unix platforms where the "file" command does not exist and the executable is set to the Python interpreter binary defaults from _default_architecture are used. """ # Use the sizeof(pointer) as default number of bits if nothing # else is given as default. if not bits: import struct try: size = struct.calcsize('P') except struct.error: # Older installations can only query longs size = struct.calcsize('l') bits = str(size*8) + 'bit' # Get data from the 'file' system command if executable: output = _syscmd_file(executable, '') else: output = '' if not output and \ executable == sys.executable: # "file" command did not return anything; we'll try to provide # some sensible defaults then... if sys.platform in _default_architecture: b, l = _default_architecture[sys.platform] if b: bits = b if l: linkage = l return bits, linkage # Split the output into a list of strings omitting the filename fileout = _architecture_split(output)[1:] if 'executable' not in fileout: # Format not supported return bits,linkage # Bits if '32-bit' in fileout: bits = '32bit' elif 'N32' in fileout: # On Irix only bits = 'n32bit' elif '64-bit' in fileout: bits = '64bit' # Linkage if 'ELF' in fileout: linkage = 'ELF' elif 'PE' in fileout: # E.g. Windows uses this format if 'Windows' in fileout: linkage = 'WindowsPE' else: linkage = 'PE' elif 'COFF' in fileout: linkage = 'COFF' elif 'MS-DOS' in fileout: linkage = 'MSDOS' else: # XXX the A.OUT format also falls under this class... pass return bits,linkage
Queries the given executable (defaults to the Python interpreter binary) for various architecture information. Returns a tuple (bits,linkage) which contains information about the bit architecture and the linkage format used for the executable. Both values are returned as strings. Values that cannot be determined are returned as given by the parameter presets. If bits is given as '', the sizeof(pointer) (or sizeof(long) on Python version < 1.5.2) is used as indicator for the supported pointer size. The function relies on the system's "file" command to do the actual work. This is available on most if not all Unix platforms. On some non-Unix platforms where the "file" command does not exist and the executable is set to the Python interpreter binary defaults from _default_architecture are used.
architecture
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def uname(): """ Fairly portable uname interface. Returns a tuple of strings (system,node,release,version,machine,processor) identifying the underlying platform. Note that unlike the os.uname function this also returns possible processor information as an additional tuple entry. Entries which cannot be determined are set to ''. """ global _uname_cache no_os_uname = 0 if _uname_cache is not None: return _uname_cache processor = '' # Get some infos from the builtin os.uname API... try: system,node,release,version,machine = os.uname() except AttributeError: no_os_uname = 1 if no_os_uname or not filter(None, (system, node, release, version, machine)): # Hmm, no there is either no uname or uname has returned #'unknowns'... we'll have to poke around the system then. if no_os_uname: system = sys.platform release = '' version = '' node = _node() machine = '' use_syscmd_ver = 1 # Try win32_ver() on win32 platforms if system == 'win32': release,version,csd,ptype = win32_ver() if release and version: use_syscmd_ver = 0 # Try to use the PROCESSOR_* environment variables # available on Win XP and later; see # http://support.microsoft.com/kb/888731 and # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM if not machine: # WOW64 processes mask the native architecture if "PROCESSOR_ARCHITEW6432" in os.environ: machine = os.environ.get("PROCESSOR_ARCHITEW6432", '') else: machine = os.environ.get('PROCESSOR_ARCHITECTURE', '') if not processor: processor = os.environ.get('PROCESSOR_IDENTIFIER', machine) # Try the 'ver' system command available on some # platforms if use_syscmd_ver: system,release,version = _syscmd_ver(system) # Normalize system to what win32_ver() normally returns # (_syscmd_ver() tends to return the vendor name as well) if system == 'Microsoft Windows': system = 'Windows' elif system == 'Microsoft' and release == 'Windows': # Under Windows Vista and Windows Server 2008, # Microsoft changed the output of the ver command. The # release is no longer printed. This causes the # system and release to be misidentified. system = 'Windows' if '6.0' == version[:3]: release = 'Vista' else: release = '' # In case we still don't know anything useful, we'll try to # help ourselves if system in ('win32','win16'): if not version: if system == 'win32': version = '32bit' else: version = '16bit' system = 'Windows' elif system[:4] == 'java': release,vendor,vminfo,osinfo = java_ver() system = 'Java' version = string.join(vminfo,', ') if not version: version = vendor # System specific extensions if system == 'OpenVMS': # OpenVMS seems to have release and version mixed up if not release or release == '0': release = version version = '' # Get processor information try: import vms_lib except ImportError: pass else: csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0) if (cpu_number >= 128): processor = 'Alpha' else: processor = 'VAX' if not processor: # Get processor information from the uname system command processor = _syscmd_uname('-p','') #If any unknowns still exist, replace them with ''s, which are more portable if system == 'unknown': system = '' if node == 'unknown': node = '' if release == 'unknown': release = '' if version == 'unknown': version = '' if machine == 'unknown': machine = '' if processor == 'unknown': processor = '' # normalize name if system == 'Microsoft' and release == 'Windows': system = 'Windows' release = 'Vista' _uname_cache = system,node,release,version,machine,processor return _uname_cache
Fairly portable uname interface. Returns a tuple of strings (system,node,release,version,machine,processor) identifying the underlying platform. Note that unlike the os.uname function this also returns possible processor information as an additional tuple entry. Entries which cannot be determined are set to ''.
uname
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def _sys_version(sys_version=None): """ Returns a parsed version of Python's sys.version as tuple (name, version, branch, revision, buildno, builddate, compiler) referring to the Python implementation name, version, branch, revision, build number, build date/time as string and the compiler identification string. Note that unlike the Python sys.version, the returned value for the Python version will always include the patchlevel (it defaults to '.0'). The function returns empty strings for tuple entries that cannot be determined. sys_version may be given to parse an alternative version string, e.g. if the version was read from a different Python interpreter. """ # Get the Python version if sys_version is None: sys_version = sys.version # Try the cache first result = _sys_version_cache.get(sys_version, None) if result is not None: return result # Parse it if 'IronPython' in sys_version: # IronPython name = 'IronPython' if sys_version.startswith('IronPython'): match = _ironpython_sys_version_parser.match(sys_version) else: match = _ironpython26_sys_version_parser.match(sys_version) if match is None: raise ValueError( 'failed to parse IronPython sys.version: %s' % repr(sys_version)) version, alt_version, compiler = match.groups() buildno = '' builddate = '' elif sys.platform.startswith('java'): # Jython name = 'Jython' match = _sys_version_parser.match(sys_version) if match is None: raise ValueError( 'failed to parse Jython sys.version: %s' % repr(sys_version)) version, buildno, builddate, buildtime, _ = match.groups() if builddate is None: builddate = '' compiler = sys.platform elif "PyPy" in sys_version: # PyPy name = "PyPy" match = _pypy_sys_version_parser.match(sys_version) if match is None: raise ValueError("failed to parse PyPy sys.version: %s" % repr(sys_version)) version, buildno, builddate, buildtime = match.groups() compiler = "" else: # CPython match = _sys_version_parser.match(sys_version) if match is None: raise ValueError( 'failed to parse CPython sys.version: %s' % repr(sys_version)) version, buildno, builddate, buildtime, compiler = \ match.groups() name = 'CPython' if builddate is None: builddate = '' elif buildtime: builddate = builddate + ' ' + buildtime if hasattr(sys, 'subversion'): # sys.subversion was added in Python 2.5 _, branch, revision = sys.subversion else: branch = '' revision = '' # Add the patchlevel version if missing l = string.split(version, '.') if len(l) == 2: l.append('0') version = string.join(l, '.') # Build and cache the result result = (name, version, branch, revision, buildno, builddate, compiler) _sys_version_cache[sys_version] = result return result
Returns a parsed version of Python's sys.version as tuple (name, version, branch, revision, buildno, builddate, compiler) referring to the Python implementation name, version, branch, revision, build number, build date/time as string and the compiler identification string. Note that unlike the Python sys.version, the returned value for the Python version will always include the patchlevel (it defaults to '.0'). The function returns empty strings for tuple entries that cannot be determined. sys_version may be given to parse an alternative version string, e.g. if the version was read from a different Python interpreter.
_sys_version
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ result = _platform_cache.get((aliased, terse), None) if result is not None: return result # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse or not os_name: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) _platform_cache[(aliased, terse)] = platform return platform
Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform.
platform
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/platform.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/platform.py
MIT
def readPlist(pathOrFile): """Read a .plist file. 'pathOrFile' may either be a file name or a (readable) file object. Return the unpacked root object (which usually is a dictionary). """ didOpen = 0 if isinstance(pathOrFile, (str, unicode)): pathOrFile = open(pathOrFile) didOpen = 1 p = PlistParser() rootObject = p.parse(pathOrFile) if didOpen: pathOrFile.close() return rootObject
Read a .plist file. 'pathOrFile' may either be a file name or a (readable) file object. Return the unpacked root object (which usually is a dictionary).
readPlist
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/plistlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/plistlib.py
MIT
def writePlist(rootObject, pathOrFile): """Write 'rootObject' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object. """ didOpen = 0 if isinstance(pathOrFile, (str, unicode)): pathOrFile = open(pathOrFile, "w") didOpen = 1 writer = PlistWriter(pathOrFile) writer.writeln("<plist version=\"1.0\">") writer.writeValue(rootObject) writer.writeln("</plist>") if didOpen: pathOrFile.close()
Write 'rootObject' to a .plist file. 'pathOrFile' may either be a file name or a (writable) file object.
writePlist
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/plistlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/plistlib.py
MIT
def writePlistToString(rootObject): """Return 'rootObject' as a plist-formatted string. """ f = StringIO() writePlist(rootObject, f) return f.getvalue()
Return 'rootObject' as a plist-formatted string.
writePlistToString
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/plistlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/plistlib.py
MIT
def readPlistFromResource(path, restype='plst', resid=0): """Read plst resource from the resource fork of path. """ warnings.warnpy3k("In 3.x, readPlistFromResource is removed.", stacklevel=2) from Carbon.File import FSRef, FSGetResourceForkName from Carbon.Files import fsRdPerm from Carbon import Res fsRef = FSRef(path) resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdPerm) Res.UseResFile(resNum) plistData = Res.Get1Resource(restype, resid).data Res.CloseResFile(resNum) return readPlistFromString(plistData)
Read plst resource from the resource fork of path.
readPlistFromResource
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/plistlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/plistlib.py
MIT
def writePlistToResource(rootObject, path, restype='plst', resid=0): """Write 'rootObject' as a plst resource to the resource fork of path. """ warnings.warnpy3k("In 3.x, writePlistToResource is removed.", stacklevel=2) from Carbon.File import FSRef, FSGetResourceForkName from Carbon.Files import fsRdWrPerm from Carbon import Res plistData = writePlistToString(rootObject) fsRef = FSRef(path) resNum = Res.FSOpenResourceFile(fsRef, FSGetResourceForkName(), fsRdWrPerm) Res.UseResFile(resNum) try: Res.Get1Resource(restype, resid).RemoveResource() except Res.Error: pass res = Res.Resource(plistData) res.AddResource(restype, resid, '') res.WriteResource() Res.CloseResFile(resNum)
Write 'rootObject' as a plst resource to the resource fork of path.
writePlistToResource
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/plistlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/plistlib.py
MIT
def fromFile(cls, pathOrFile): """Deprecated. Use the readPlist() function instead.""" rootObject = readPlist(pathOrFile) plist = cls() plist.update(rootObject) return plist
Deprecated. Use the readPlist() function instead.
fromFile
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/plistlib.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/plistlib.py
MIT
def __init__(self, cmd, capturestderr=False, bufsize=-1): """The parameter 'cmd' is the shell command to execute in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.""" _cleanup() self.cmd = cmd p2cread, p2cwrite = os.pipe() c2pread, c2pwrite = os.pipe() if capturestderr: errout, errin = os.pipe() self.pid = os.fork() if self.pid == 0: # Child os.dup2(p2cread, 0) os.dup2(c2pwrite, 1) if capturestderr: os.dup2(errin, 2) self._run_child(cmd) os.close(p2cread) self.tochild = os.fdopen(p2cwrite, 'w', bufsize) os.close(c2pwrite) self.fromchild = os.fdopen(c2pread, 'r', bufsize) if capturestderr: os.close(errin) self.childerr = os.fdopen(errout, 'r', bufsize) else: self.childerr = None
The parameter 'cmd' is the shell command to execute in a sub-process. On UNIX, 'cmd' may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If 'cmd' is a string it will be passed to the shell (as with os.system()). The 'capturestderr' flag, if true, specifies that the object should capture standard error output of the child process. The default is false. If the 'bufsize' parameter is specified, it specifies the size of the I/O buffers to/from the child process.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/popen2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/popen2.py
MIT
def poll(self, _deadstate=None): """Return the exit status of the child process if it has finished, or -1 if it hasn't finished yet.""" if self.sts < 0: try: pid, sts = os.waitpid(self.pid, os.WNOHANG) # pid will be 0 if self.pid hasn't terminated if pid == self.pid: self.sts = sts except os.error: if _deadstate is not None: self.sts = _deadstate return self.sts
Return the exit status of the child process if it has finished, or -1 if it hasn't finished yet.
poll
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/popen2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/popen2.py
MIT
def wait(self): """Wait for and return the exit status of the child process.""" if self.sts < 0: pid, sts = os.waitpid(self.pid, 0) # This used to be a test, but it is believed to be # always true, so I changed it to an assertion - mvl assert pid == self.pid self.sts = sts return self.sts
Wait for and return the exit status of the child process.
wait
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/popen2.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/popen2.py
MIT