INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Invokes a callback every time a hotkey is pressed. The hotkey must be in the format ctrl + shift + a s. This would trigger when the user holds ctrl shift and a at once releases and then presses s. To represent literal commas pluses and spaces use their names ( comma plus space ).
def add_hotkey(hotkey, callback, args=(), suppress=False, timeout=1, trigger_on_release=False): """ Invokes a callback every time a hotkey is pressed. The hotkey must be in the format `ctrl+shift+a, s`. This would trigger when the user holds ctrl, shift and "a" at once, releases, and then presses "s". T...
Whenever the hotkey src is pressed suppress it and send dst instead.
def remap_hotkey(src, dst, suppress=True, trigger_on_release=False): """ Whenever the hotkey `src` is pressed, suppress it and send `dst` instead. Example: remap('alt+w', 'ctrl+up') """ def handler(): active_modifiers = sorted(modifier for modifier, state in _listener.modifier_...
Builds a list of all currently pressed scan codes releases them and returns the list. Pairs well with restore_state and restore_modifiers.
def stash_state(): """ Builds a list of all currently pressed scan codes, releases them and returns the list. Pairs well with `restore_state` and `restore_modifiers`. """ # TODO: stash caps lock / numlock /scrollock state. with _pressed_events_lock: state = sorted(_pressed_events) fo...
Given a list of scan_codes ensures these keys and only these keys are pressed. Pairs well with stash_state alternative to restore_modifiers.
def restore_state(scan_codes): """ Given a list of scan_codes ensures these keys, and only these keys, are pressed. Pairs well with `stash_state`, alternative to `restore_modifiers`. """ _listener.is_replaying = True with _pressed_events_lock: current = set(_pressed_events) target =...
Sends artificial keyboard events to the OS simulating the typing of a given text. Characters not available on the keyboard are typed as explicit unicode characters using OS - specific functionality such as alt + codepoint.
def write(text, delay=0, restore_state_after=True, exact=None): """ Sends artificial keyboard events to the OS, simulating the typing of a given text. Characters not available on the keyboard are typed as explicit unicode characters using OS-specific functionality, such as alt+codepoint. To ensure ...
Blocks the program execution until the given hotkey is pressed or if given no parameters blocks forever.
def wait(hotkey=None, suppress=False, trigger_on_release=False): """ Blocks the program execution until the given hotkey is pressed or, if given no parameters, blocks forever. """ if hotkey: lock = _Event() remove = add_hotkey(hotkey, lambda: lock.set(), suppress=suppress, trigger_on...
Returns a string representation of hotkey from the given key names or the currently pressed keys if not given. This function:
def get_hotkey_name(names=None): """ Returns a string representation of hotkey from the given key names, or the currently pressed keys if not given. This function: - normalizes names; - removes "left" and "right" prefixes; - replaces the "+" key name with "plus" to avoid ambiguity; - puts ...
Blocks until a keyboard event happens then returns that event.
def read_event(suppress=False): """ Blocks until a keyboard event happens, then returns that event. """ queue = _queue.Queue(maxsize=1) hooked = hook(queue.put, suppress=suppress) while True: event = queue.get() unhook(hooked) return event
Blocks until a keyboard event happens then returns that event s name or if missing its scan code.
def read_key(suppress=False): """ Blocks until a keyboard event happens, then returns that event's name or, if missing, its scan code. """ event = read_event(suppress) return event.name or event.scan_code
Similar to read_key () but blocks until the user presses and releases a hotkey ( or single key ) then returns a string representing the hotkey pressed.
def read_hotkey(suppress=True): """ Similar to `read_key()`, but blocks until the user presses and releases a hotkey (or single key), then returns a string representing the hotkey pressed. Example: read_hotkey() # "ctrl+shift+p" """ queue = _queue.Queue() fn = lambda e:...
Given a sequence of events tries to deduce what strings were typed. Strings are separated when a non - textual key is pressed ( such as tab or enter ). Characters are converted to uppercase according to shift and capslock status. If allow_backspace is True backspaces remove the last character typed.
def get_typed_strings(events, allow_backspace=True): """ Given a sequence of events, tries to deduce what strings were typed. Strings are separated when a non-textual key is pressed (such as tab or enter). Characters are converted to uppercase according to shift and capslock status. If `allow_backsp...
Starts recording all keyboard events into a global variable or the given queue if any. Returns the queue of events and the hooked function.
def start_recording(recorded_events_queue=None): """ Starts recording all keyboard events into a global variable, or the given queue if any. Returns the queue of events and the hooked function. Use `stop_recording()` or `unhook(hooked_function)` to stop. """ recorded_events_queue = recorded_eve...
Stops the global recording of events and returns a list of the events captured.
def stop_recording(): """ Stops the global recording of events and returns a list of the events captured. """ global _recording if not _recording: raise ValueError('Must call "start_recording" before.') recorded_events_queue, hooked = _recording unhook(hooked) return list(rec...
Records all keyboard events from all keyboards until the user presses the given hotkey. Then returns the list of events recorded of type keyboard. KeyboardEvent. Pairs well with play ( events ).
def record(until='escape', suppress=False, trigger_on_release=False): """ Records all keyboard events from all keyboards until the user presses the given hotkey. Then returns the list of events recorded, of type `keyboard.KeyboardEvent`. Pairs well with `play(events)`. Note: this is a blocking ...
Plays a sequence of recorded events maintaining the relative time intervals. If speed_factor is < = 0 then the actions are replayed as fast as the OS allows. Pairs well with record ().
def play(events, speed_factor=1.0): """ Plays a sequence of recorded events, maintaining the relative time intervals. If speed_factor is <= 0 then the actions are replayed as fast as the OS allows. Pairs well with `record()`. Note: the current keyboard state is cleared at the beginning and restored...
Invokes a callback every time a sequence of characters is typed ( e. g. pet ) and followed by a trigger key ( e. g. space ). Modifiers ( e. g. alt ctrl shift ) are ignored.
def add_word_listener(word, callback, triggers=['space'], match_suffix=False, timeout=2): """ Invokes a callback every time a sequence of characters is typed (e.g. 'pet') and followed by a trigger key (e.g. space). Modifiers (e.g. alt, ctrl, shift) are ignored. - `word` the typed text to be matched...
Registers a hotkey that replaces one typed text with another. For example
def add_abbreviation(source_text, replacement_text, match_suffix=False, timeout=2): """ Registers a hotkey that replaces one typed text with another. For example add_abbreviation('tm', u'™') Replaces every "tm" followed by a space with a ™ symbol (and no space). The replacement is done by send...
This function is called for every OS keyboard event and decides if the event should be blocked or not and passes a copy of the event to other non - blocking listeners.
def direct_callback(self, event): """ This function is called for every OS keyboard event and decides if the event should be blocked or not, and passes a copy of the event to other, non-blocking, listeners. There are two ways to block events: remapped keys, which translate ...
Ensures the scan code/ virtual key code/ name translation tables are filled.
def _setup_name_tables(): """ Ensures the scan code/virtual key code/name translation tables are filled. """ with tables_lock: if to_name: return # Go through every possible scan code, and map them to virtual key codes. # Then vice-versa. all_scan_codes = [(sc, user3...
Registers a Windows low level keyboard hook. The provided callback will be invoked for each high - level keyboard event and is expected to return True if the key event should be passed to the next program or False if the event is to be blocked.
def prepare_intercept(callback): """ Registers a Windows low level keyboard hook. The provided callback will be invoked for each high-level keyboard event, and is expected to return True if the key event should be passed to the next program, or False if the event is to be blocked. No event is p...
Starts the listening thread if it wans t already.
def start_if_necessary(self): """ Starts the listening thread if it wans't already. """ self.lock.acquire() try: if not self.listening: self.init() self.listening = True self.listening_thread = Thread(target=self.listen...
Loops over the underlying queue of events and processes them in order.
def process(self): """ Loops over the underlying queue of events and processes them in order. """ assert self.queue is not None while True: event = self.queue.get() if self.pre_process_event(event): self.invoke_handlers(event) s...
Removes a previously added event handler.
def remove_handler(self, handler): """ Removes a previously added event handler. """ while handler in self.handlers: self.handlers.remove(handler)
Moves the mouse. If absolute to position ( x y ) otherwise move relative to the current position. If duration is non - zero animates the movement.
def move(x, y, absolute=True, duration=0): """ Moves the mouse. If `absolute`, to position (x, y), otherwise move relative to the current position. If `duration` is non-zero, animates the movement. """ x = int(x) y = int(y) # Requires an extra system call on Linux, but `move_relative` is me...
Holds the left mouse button moving from start to end position then releases. absolute and duration are parameters regarding the mouse movement.
def drag(start_x, start_y, end_x, end_y, absolute=True, duration=0): """ Holds the left mouse button, moving from start to end position, then releases. `absolute` and `duration` are parameters regarding the mouse movement. """ if is_pressed(): release() move(start_x, start_y, absolut...
Invokes callback with args when the specified event happens.
def on_button(callback, args=(), buttons=(LEFT, MIDDLE, RIGHT, X, X2), types=(UP, DOWN, DOUBLE)): """ Invokes `callback` with `args` when the specified event happens. """ if not isinstance(buttons, (tuple, list)): buttons = (buttons,) if not isinstance(types, (tuple, list)): types = (types,)...
Blocks program execution until the given button performs an event.
def wait(button=LEFT, target_types=(UP, DOWN, DOUBLE)): """ Blocks program execution until the given button performs an event. """ from threading import Lock lock = Lock() lock.acquire() handler = on_button(lock.release, (), [button], target_types) lock.acquire() _listener.remove_han...
Records all mouse events until the user presses the given button. Then returns the list of events recorded. Pairs well with play ( events ).
def record(button=RIGHT, target_types=(DOWN,)): """ Records all mouse events until the user presses the given button. Then returns the list of events recorded. Pairs well with `play(events)`. Note: this is a blocking function. Note: for more details on the mouse hook and events see `hook`. """ ...
Plays a sequence of recorded events maintaining the relative time intervals. If speed_factor is < = 0 then the actions are replayed as fast as the OS allows. Pairs well with record ().
def play(events, speed_factor=1.0, include_clicks=True, include_moves=True, include_wheel=True): """ Plays a sequence of recorded events, maintaining the relative time intervals. If speed_factor is <= 0 then the actions are replayed as fast as the OS allows. Pairs well with `record()`. The paramete...
Given a key name ( e. g. LEFT CONTROL ) clean up the string and convert to the canonical representation ( e. g. left ctrl ) if one is known.
def normalize_name(name): """ Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to the canonical representation (e.g. "left ctrl") if one is known. """ if not name or not isinstance(name, basestring): raise ValueError('Can only normalize non-empty string names. Unexpect...
Appends events to the queue ( ButtonEvent WheelEvent and MoveEvent ).
def listen(queue): """ Appends events to the queue (ButtonEvent, WheelEvent, and MoveEvent). """ if not os.geteuid() == 0: raise OSError("Error 13 - Must be run as administrator") listener = MouseEventListener(lambda e: queue.put(e) or is_allowed(e.name, e.event_type == KEY_UP)) t = threading.Th...
Sends a down event for the specified button using the provided constants
def press(button=LEFT): """ Sends a down event for the specified button, using the provided constants """ location = get_position() button_code, button_down, _, _ = _button_mapping[button] e = Quartz.CGEventCreateMouseEvent( None, button_down, location, button_code) ...
Sends an up event for the specified button using the provided constants
def release(button=LEFT): """ Sends an up event for the specified button, using the provided constants """ location = get_position() button_code, _, button_up, _ = _button_mapping[button] e = Quartz.CGEventCreateMouseEvent( None, button_up, location, button_code) if ...
Sends a wheel event for the provided number of clicks. May be negative to reverse direction.
def wheel(delta=1): """ Sends a wheel event for the provided number of clicks. May be negative to reverse direction. """ location = get_position() e = Quartz.CGEventCreateMouseEvent( None, Quartz.kCGEventScrollWheel, location, Quartz.kCGMouseButtonLeft) e2 = Quartz.CG...
Sets the mouse s location to the specified coordinates.
def move_to(x, y): """ Sets the mouse's location to the specified coordinates. """ for b in _button_state: if _button_state[b]: e = Quartz.CGEventCreateMouseEvent( None, _button_mapping[b][3], # Drag Event (x, y), _button_mappin...
Returns the mouse s location as a tuple of ( x y ).
def get_position(): """ Returns the mouse's location as a tuple of (x, y). """ e = Quartz.CGEventCreate(None) point = Quartz.CGEventGetLocation(e) return (point.x, point.y)
Returns a tuple of ( scan_code modifiers ) where scan_code is a numeric scan code and modifiers is an array of string modifier names ( like shift )
def character_to_vk(self, character): """ Returns a tuple of (scan_code, modifiers) where ``scan_code`` is a numeric scan code and ``modifiers`` is an array of string modifier names (like 'shift') """ for vk in self.non_layout_keys: if self.non_layout_keys[vk] == character.lower(): ...
Returns a character corresponding to the specified scan code ( with given modifiers applied )
def vk_to_character(self, vk, modifiers=[]): """ Returns a character corresponding to the specified scan code (with given modifiers applied) """ if vk in self.non_layout_keys: # Not a character return self.non_layout_keys[vk] elif vk in self.layout_specific_keys: ...
Sends a down event for the specified scan code
def press(self, key_code): """ Sends a 'down' event for the specified scan code """ if key_code >= 128: # Media key ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( 14, # type (0, 0), # loc...
Creates a listener and loops while waiting for an event. Intended to run as a background thread.
def run(self): """ Creates a listener and loops while waiting for an event. Intended to run as a background thread. """ self.tap = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Qu...
Formats a dumpkeys format to our standard.
def cleanup_key(name): """ Formats a dumpkeys format to our standard. """ name = name.lstrip('+') is_keypad = name.startswith('KP_') for mod in ('Meta_', 'Control_', 'dead_', 'KP_'): if name.startswith(mod): name = name[len(mod):] # Dumpkeys is weird like that. if name == 'R...
Helper method for defining space - delimited indentation blocks such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that is repeated within the indented block - indentStack - list created by caller to manage indentation stack ( ...
def indentedBlock(blockStatementExpr, indentStack, indent=True): """ Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - blockStatementExpr - expression defining syntax of statement that ...
Returns a new copy of a C { ParseResults } object.
def copy( self ): """ Returns a new copy of a C{ParseResults} object. """ ret = ParseResults( self.__toklist ) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update( self.__accumNames ) ret.__name = self.__name ...
( Deprecated ) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ): """ (Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names. """ nl = "\n" out = [] namedItems = dict((v[1],k) for (k,vlist)...
Scan the input string for expression matches. Each match will return the matching tokens start location and end location. May be called with optional C { maxMatches } argument to clip scanning after n matches are found. If C { overlap } is specified then overlapping matches will be reported. Note that the start and end...
def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ): """ Scan the input string for expression matches. Each match will return the matching tokens, start location, and end location. May be called with optional C{maxMatches} argument, to clip scanning after 'n' match...
Extension to C { L { scanString }} to modify matching text with modified tokens that may be returned from a parse action. To use C { transformString } define a grammar and attach a parse action to it that modifies the returned token list. Invoking C { transformString () } on a target string will then scan for matches a...
def transformString( self, instring ): """ Extension to C{L{scanString}}, to modify matching text with modified tokens that may be returned from a parse action. To use C{transformString}, define a grammar and attach a parse action to it that modifies the returned token list. ...
Supplement reinitialize_command to work around http:// bugs. python. org/ issue20819
def reinitialize_command(self, command, reinit_subcommands=0): """ Supplement reinitialize_command to work around http://bugs.python.org/issue20819 """ cmd = self.distribution.reinitialize_command( command, reinit_subcommands) if command in ('install', 'instal...
Determine if two paths reference the same file.
def samefile(p1, p2): """ Determine if two paths reference the same file. Augments os.path.samefile to work on Windows and suppresses errors if the path doesn't exist. """ both_exist = os.path.exists(p1) and os.path.exists(p2) use_samefile = hasattr(os.path, 'samefile') and both_exist i...
Return a list of site dirs
def get_site_dirs(): """ Return a list of 'site' dirs """ sitedirs = [] # start with PYTHONPATH sitedirs.extend(_pythonpath()) prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: ...
Yield sys. path directories that might contain old - style packages
def expand_paths(inputs): """Yield sys.path directories that might contain "old-style" packages""" seen = {} for dirname in inputs: dirname = normalize_path(dirname) if dirname in seen: continue seen[dirname] = 1 if not os.path.isdir(dirname): conti...
Get exe - > egg path translations for a given. exe file
def get_exe_prefixes(exe_filename): """Get exe->egg path translations for a given .exe file""" prefixes = [ ('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''), ('PLATLIB/', ''), ('SCRIPTS/', 'EGG-INFO/scripts/'), ('DATA/lib/site-packages', ''), ] z = zipfile.ZipF...
Return a regular expression based on first_line_re suitable for matching strings.
def _first_line_re(): """ Return a regular expression based on first_line_re suitable for matching strings. """ if isinstance(first_line_re.pattern, str): return first_line_re # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern. return re.compile(first_line_re.pattern.d...
Fix any globally cached dist_path related data
def update_dist_caches(dist_path, fix_zipimporter_caches): """ Fix any globally cached `dist_path` related data `dist_path` should be a path of a newly installed egg distribution (zipped or unzipped). sys.path_importer_cache contains finder objects that have been cached when importing data fro...
Return zipimporter cache entry keys related to a given normalized path.
def _collect_zipimporter_cache_entries(normalized_path, cache): """ Return zipimporter cache entry keys related to a given normalized path. Alternative path spellings (e.g. those using different character case or those using alternative path separators) related to the same path are included. Any su...
Is this string a valid Python script?
def is_python(text, filename='<string>'): "Is this string a valid Python script?" try: compile(text, filename, 'exec') except (SyntaxError, TypeError): return False else: return True
Determine if the specified executable is a. sh ( contains a #! line )
def is_sh(executable): """Determine if the specified executable is a .sh (contains a #! line)""" try: with io.open(executable, encoding='latin-1') as fp: magic = fp.read(2) except (OSError, IOError): return executable return magic == '#!'
Is this text as a whole a Python script? ( as opposed to shell/ bat/ etc.
def is_python_script(script_text, filename): """Is this text, as a whole, a Python script? (as opposed to shell/bat/etc. """ if filename.endswith('.py') or filename.endswith('.pyw'): return True # extension says it's Python if is_python(script_text, filename): return True # it's syntac...
Load the Windows launcher ( executable ) suitable for launching a script.
def get_win_launcher(type): """ Load the Windows launcher (executable) suitable for launching a script. `type` should be either 'cli' or 'gui' Returns the executable as a byte string. """ launcher_fn = '%s.exe' % type if is_64bit(): launcher_fn = launcher_fn.replace(".", "-64.") ...
Render the Setuptools version and installation details then exit.
def _render_version(): """ Render the Setuptools version and installation details, then exit. """ ver = sys.version[:3] dist = get_distribution('setuptools') tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})' print(tmpl.format(**locals())) ...
Fix the install_dir if -- user was used.
def _fix_install_dir_for_user_site(self): """ Fix the install_dir if "--user" was used. """ if not self.user or not site.ENABLE_USER_SITE: return self.create_home_path() if self.install_userbase is None: msg = "User base directory is not specified...
Empirically verify whether. pth files are supported in inst. dir
def check_pth_processing(self): """Empirically verify whether .pth files are supported in inst. dir""" instdir = self.install_dir log.info("Checking .pth file support in %s", instdir) pth_file = self.pseudo_tempname() + ".pth" ok_file = pth_file + '.ok' ok_exists = os.pat...
Write all the scripts for dist unless scripts are excluded
def install_egg_scripts(self, dist): """Write all the scripts for `dist`, unless scripts are excluded""" if not self.exclude_scripts and dist.metadata_isdir('scripts'): for script_name in dist.metadata_listdir('scripts'): if dist.metadata_isdir('scripts/' + script_name): ...
Sets the install directories by applying the install schemes.
def select_scheme(self, name): """Sets the install directories by applying the install schemes.""" # it's the caller's problem if they supply a bad name! scheme = INSTALL_SCHEMES[name] for key in SCHEME_KEYS: attrname = 'install_' + key if getattr(self, attrname) ...
Write an executable file to the scripts directory
def write_script(self, script_name, contents, mode="t", blockers=()): """Write an executable file to the scripts directory""" self.delete_blockers( # clean up old .py/.pyw w/o a script [os.path.join(self.script_dir, x) for x in blockers] ) log.info("Installing %s script to %...
Extract a bdist_wininst to the directories an egg would use
def exe_to_egg(self, dist_filename, egg_tmp): """Extract a bdist_wininst to the directories an egg would use""" # Check for .pth file and set up prefix translations prefixes = get_exe_prefixes(dist_filename) to_compile = [] native_libs = [] top_level = {} def pro...
Helpful installation message for display to package users
def installation_report(self, req, dist, what="Installed"): """Helpful installation message for display to package users""" msg = "\n%(what)s %(eggloc)s%(extras)s" if self.multi_version and not self.no_report: msg += '\n' + self.__mv_warning if self.install_dir not in map...
Add dist to the distribution map
def add(self, dist): """Add `dist` to the distribution map""" new_path = ( dist.location not in self.paths and ( dist.location not in self.sitedirs or # account for '.' being in PYTHONPATH dist.location == os.getcwd() ) ) ...
Remove dist from the distribution map
def remove(self, dist): """Remove `dist` from the distribution map""" while dist.location in self.paths: self.paths.remove(dist.location) self.dirty = True Environment.remove(self, dist)
Construct a CommandSpec from a parameter to build_scripts which may be None.
def from_param(cls, param): """ Construct a CommandSpec from a parameter to build_scripts, which may be None. """ if isinstance(param, cls): return param if isinstance(param, list): return cls(param) if param is None: return cls...
Construct a command spec from a simple string representing a command line parseable by shlex. split.
def from_string(cls, string): """ Construct a command spec from a simple string representing a command line parseable by shlex.split. """ items = shlex.split(string, **cls.split_args) return cls(items)
Extract any options from the first line of the script.
def _extract_options(orig_script): """ Extract any options from the first line of the script. """ first = (orig_script + '\n').splitlines()[0] match = _first_line_re().match(first) options = match.group(1) or '' if match else '' return options.strip()
Yield write_script () argument tuples for a distribution s console_scripts and gui_scripts entry points.
def get_args(cls, dist, header=None): """ Yield write_script() argument tuples for a distribution's console_scripts and gui_scripts entry points. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console',...
Select the best ScriptWriter for this environment.
def best(cls): """ Select the best ScriptWriter for this environment. """ if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'): return WindowsScriptWriter.best() else: return cls
Create a #! line getting options ( if any ) from script_text
def get_header(cls, script_text="", executable=None): """Create a #! line, getting options (if any) from script_text""" cmd = cls.command_spec_class.best().from_param(executable) cmd.install_options(script_text) return cmd.as_header()
Select the best ScriptWriter suitable for Windows
def best(cls): """ Select the best ScriptWriter suitable for Windows """ writer_lookup = dict( executable=WindowsExecutableLauncherWriter, natural=cls, ) # for compatibility, use the executable launcher by default launcher = os.environ.get(...
For Windows add a. py extension
def _get_script_args(cls, type_, name, header, script_text): "For Windows, add a .py extension" ext = dict(console='.pya', gui='.pyw')[type_] if ext not in os.environ['PATHEXT'].lower().split(';'): msg = ( "{ext} not listed in PATHEXT; scripts will not be " ...
Make sure pythonw is used for gui and and python is used for console ( regardless of what sys. executable is ).
def _adjust_header(cls, type_, orig_header): """ Make sure 'pythonw' is used for gui and and 'python' is used for console (regardless of what sys.executable is). """ pattern = 'pythonw.exe' repl = 'python.exe' if type_ == 'gui': pattern, repl = repl, p...
For Windows add a. py extension and an. exe launcher
def _get_script_args(cls, type_, name, header, script_text): """ For Windows, add a .py extension and an .exe launcher """ if type_ == 'gui': launcher_type = 'gui' ext = '-script.pyw' old = ['.pyw'] else: launcher_type = 'cli' ...
Attempt to load password from keyring. Suppress Exceptions.
def _load_password_from_keyring(self): """ Attempt to load password from keyring. Suppress Exceptions. """ try: keyring = __import__('keyring') return keyring.get_password(self.repository, self.username) except Exception: pass
Convert a filename to a string ( on Python 2 explicitly a byte string not Unicode ) as distutils checks for the exact type str.
def _to_str(s): """ Convert a filename to a string (on Python 2, explicitly a byte string, not Unicode) as distutils checks for the exact type str. """ if sys.version_info[0] == 2 and not isinstance(s, str): # Assume it's Unicode, as that's what the PEP says # should be provided....
Replace distutils. dist. Distribution with this class for the duration of this context.
def patch(cls): """ Replace distutils.dist.Distribution with this class for the duration of this context. """ orig = distutils.core.Distribution distutils.core.Distribution = cls try: yield finally: distutils.core.Distributi...
Run the script in sys. argv [ 1 ] as if it had been invoked naturally.
def run(): """ Run the script in sys.argv[1] as if it had been invoked naturally. """ __builtins__ script_name = sys.argv[1] namespace = dict( __file__=script_name, __name__='__main__', __doc__=None, ) sys.argv[:] = sys.argv[1:] open_ = getattr(tokenize, ...
Build modules packages and copy data files to build directory
def run(self): """Build modules, packages, and copy data files to build directory""" if not self.py_modules and not self.packages: return if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_...
Generate list of ( package src_dir build_dir filenames ) tuples
def _get_data_files(self): """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" self.analyze_manifest() return list(map(self._get_pkg_data_files, self.packages or ()))
Return filenames for package s data files in src_dir
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" patterns = self._get_platform_patterns( self.package_data, package, src_dir, ) globs_expanded = map(glob, patterns) # flatten the expanded...
Copy data files into build directory
def build_package_data(self): """Copy data files into build directory""" for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) s...
Check namespace packages __init__ for declare_namespace
def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = orig.build_py.check_package(self, package, package_dir) self.packages_...
Filter filenames for package s data files in src_dir
def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" files = list(files) patterns = self._get_platform_patterns( self.exclude_package_data, package, src_dir, ) match_groups = ( ...
yield platform - specific path patterns ( suitable for glob or fn_match ) from a glob - based spec ( such as self. package_data or self. exclude_package_data ) matching package in src_dir.
def _get_platform_patterns(spec, package, src_dir): """ yield platform-specific path patterns (suitable for glob or fn_match) from a glob-based spec (such as self.package_data or self.exclude_package_data) matching package in src_dir. """ raw_patterns = itertools....
Prevent improper installs without necessary metadata. See #659
def require_metadata(): "Prevent improper installs without necessary metadata. See #659" egg_info_dir = os.path.join(here, 'setuptools.egg-info') if not os.path.exists(egg_info_dir): msg = ( "Cannot build setuptools without metadata. " "Run `bootstrap.py`." ) ...
Given the filename including md5 fragment construct the dependency link for PyPI.
def pypi_link(pkg_filename): """ Given the filename, including md5 fragment, construct the dependency link for PyPI. """ root = 'https://files.pythonhosted.org/packages/source' name, sep, rest = pkg_filename.partition('-') parts = root, name[0], name, pkg_filename return '/'.join(parts)
Returns glibc version string or None if not using glibc.
def glibc_version_string(): "Returns glibc version string, or None if not using glibc." # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen # manpage says, "If filename is NULL, then the returned handle is for the # main program". This way we can let the linker do the work to figure ou...
Unpack filename to extract_dir or raise UnrecognizedFormat
def unpack_archive(filename, extract_dir, progress_filter=default_filter, drivers=None): """Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat`` `progress_filter` is a function taking two arguments: a source path internal to the archive ('/'-separated), and a filesystem path where it...
Unpack zip filename to extract_dir
def unpack_zipfile(filename, extract_dir, progress_filter=default_filter): """Unpack zip `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined by ``zipfile.is_zipfile()``). See ``unpack_archive()`` for an explanation of the `progress_filter` argument. ...
Unpack tar/ tar. gz/ tar. bz2 filename to extract_dir
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter): """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir` Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined by ``tarfile.open()``). See ``unpack_archive()`` for an explanation of the `progress_filter` a...
Patched distutils. msvc9compiler. find_vcvarsall to use the standalone compiler build for Python ( VCForPython ). Fall back to original behavior when the standalone compiler is not available.
def msvc9_find_vcvarsall(version): """ Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone compiler build for Python (VCForPython). Fall back to original behavior when the standalone compiler is not available. Redirect the path of "vcvarsall.bat". Known supported compilers ...
Patched distutils. msvc9compiler. query_vcvarsall for support extra compilers.
def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs): """ Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers. Set environment without use of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visual C++ 9.0: Microsoft Vi...
Patched distutils. _msvccompiler. _get_vc_env for support extra compilers.
def msvc14_get_vc_env(plat_spec): """ Patched "distutils._msvccompiler._get_vc_env" for support extra compilers. Set environment without use of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visual C++ 14.0: Microsoft Visual C++ Build Tools 2015 (x86...
Patched distutils. _msvccompiler. gen_lib_options for fix compatibility between numpy. distutils and distutils. _msvccompiler ( for Numpy < 1. 11. 2 )
def msvc14_gen_lib_options(*args, **kwargs): """ Patched "distutils._msvccompiler.gen_lib_options" for fix compatibility between "numpy.distutils" and "distutils._msvccompiler" (for Numpy < 1.11.2) """ if "numpy.distutils" in sys.modules: import numpy as np if LegacyVersion(np.__...
Add details to the exception message to help guide the user as to what action will resolve it.
def _augment_exception(exc, version, arch=''): """ Add details to the exception message to help guide the user as to what action will resolve it. """ # Error if MSVC++ directory not found or environment not set message = exc.args[0] if "vcvarsall" in message.lower() or "visual c" in message...