text stringlengths 81 112k |
|---|
Returns a list of the files under the specified path
def listdir(self, url):
"""Returns a list of the files under the specified path"""
(store_name, path) = self._split_url(url)
adapter = self._create_adapter(store_name)
return [
"adl://{store_name}.azuredatalakestore.net/{p... |
Read storage at a given url
def read(self, url):
"""Read storage at a given url"""
(store_name, path) = self._split_url(url)
adapter = self._create_adapter(store_name)
lines = []
with adapter.open(path) as f:
for line in f:
lines.append(line.decode())... |
Write buffer to storage at a given url
def write(self, buf, url):
"""Write buffer to storage at a given url"""
(store_name, path) = self._split_url(url)
adapter = self._create_adapter(store_name)
with adapter.open(path, 'wb') as f:
f.write(buf.encode()) |
Wraps the parent class process call slightly
def preprocess(self, nb_man, resources, km=None):
"""
Wraps the parent class process call slightly
"""
with self.setup_preprocessor(nb_man.nb, resources, km=km):
if self.log_output:
self.log.info("Executing noteboo... |
This function acts as a replacement for the grandparent's `preprocess`
method.
We are doing this for the following reasons:
1. Notebooks will stop executing when they encounter a failure but not
raise a `CellException`. This allows us to save the notebook with the
traceba... |
Add built-in parameters to a dictionary of parameters
Parameters
----------
parameters : dict
Dictionary of parameters provided by the user
def add_builtin_parameters(parameters):
"""Add built-in parameters to a dictionary of parameters
Parameters
----------
parameters : dict
... |
Format a path with a provided dictionary of parameters
Parameters
----------
path : string
Path with optional parameters, as a python format string
parameters : dict
Arbitrary keyword arguments to fill in the path
def parameterize_path(path, parameters):
"""Format a path with a provi... |
Assigned parameters into the appropriate place in the input notebook
Parameters
----------
nb : NotebookNode
Executable notebook object
parameters : dict
Arbitrary keyword arguments to pass as notebook parameters
report_mode : bool, optional
Flag to set report mode
def paramet... |
Returns True if `key` is a scan code or name of a modifier key.
def is_modifier(key):
"""
Returns True if `key` is a scan code or name of a modifier key.
"""
if _is_str(key):
return key in all_modifiers
else:
if not _modifier_scan_codes:
scan_codes = (key_to_scan_codes(n... |
Returns a list of scan codes associated with this key (name or scan code).
def key_to_scan_codes(key, error_if_missing=True):
"""
Returns a list of scan codes associated with this key (name or scan code).
"""
if _is_number(key):
return (key,)
elif _is_list(key):
return sum((key_to_s... |
Parses a user-provided hotkey into nested tuples representing the
parsed structure, with the bottom values being lists of scan codes.
Also accepts raw scan codes, which are then wrapped in the required
number of nestings.
Example:
parse_hotkey("alt+shift+a, alt+b, c")
# Keys: ^~^... |
Sends OS events that perform the given *hotkey* hotkey.
- `hotkey` can be either a scan code (e.g. 57 for space), single key
(e.g. 'space') or multi-key, multi-step hotkey (e.g. 'alt+F4, enter').
- `do_press` if true then press events are sent. Defaults to True.
- `do_release` if true then release even... |
Returns True if the key is pressed.
is_pressed(57) #-> True
is_pressed('space') #-> True
is_pressed('ctrl+space') #-> True
def is_pressed(hotkey):
"""
Returns True if the key is pressed.
is_pressed(57) #-> True
is_pressed('space') #-> True
is_pressed('ctrl+spac... |
Calls the provided function in a new thread after waiting some time.
Useful for giving the system some time to process an event, without blocking
the current execution flow.
def call_later(fn, args=(), delay=0.001):
"""
Calls the provided function in a new thread after waiting some time.
Useful for... |
Installs a global listener on all available keyboards, invoking `callback`
each time a key is pressed or released.
The event passed to the callback is of type `keyboard.KeyboardEvent`,
with the following attributes:
- `name`: an Unicode representation of the character (e.g. "&") or
description... |
Invokes `callback` for every KEY_DOWN event. For details see `hook`.
def on_press(callback, suppress=False):
"""
Invokes `callback` for every KEY_DOWN event. For details see `hook`.
"""
return hook(lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress) |
Invokes `callback` for every KEY_UP event. For details see `hook`.
def on_release(callback, suppress=False):
"""
Invokes `callback` for every KEY_UP event. For details see `hook`.
"""
return hook(lambda e: e.event_type == KEY_DOWN or callback(e), suppress=suppress) |
Hooks key up and key down events for a single key. Returns the event handler
created. To remove a hooked key use `unhook_key(key)` or
`unhook_key(handler)`.
Note: this function shares state with hotkeys, so `clear_all_hotkeys`
affects it aswell.
def hook_key(key, callback, suppress=False):
"""
... |
Invokes `callback` for KEY_DOWN event related to the given key. For details see `hook`.
def on_press_key(key, callback, suppress=False):
"""
Invokes `callback` for KEY_DOWN event related to the given key. For details see `hook`.
"""
return hook_key(key, lambda e: e.event_type == KEY_UP or callback(e), ... |
Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
def on_release_key(key, callback, suppress=False):
"""
Invokes `callback` for KEY_UP event related to the given key. For details see `hook`.
"""
return hook_key(key, lambda e: e.event_type == KEY_DOWN or callback(e), ... |
Removes all keyboard hooks in use, including hotkeys, abbreviations, word
listeners, `record`ers and `wait`s.
def unhook_all():
"""
Removes all keyboard hooks in use, including hotkeys, abbreviations, word
listeners, `record`ers and `wait`s.
"""
_listener.start_if_necessary()
_listener.bloc... |
Whenever the key `src` is pressed or released, regardless of modifiers,
press or release the hotkey `dst` instead.
def remap_key(src, dst):
"""
Whenever the key `src` is pressed or released, regardless of modifiers,
press or release the hotkey `dst` instead.
"""
def handler(event):
if e... |
Parses a user-provided hotkey. Differently from `parse_hotkey`,
instead of each step being a list of the different scan codes for each key,
each step is a list of all possible combinations of those scan codes.
def parse_hotkey_combinations(hotkey):
"""
Parses a user-provided hotkey. Differently from `p... |
Hooks a single-step hotkey (e.g. 'shift+a').
def _add_hotkey_step(handler, combinations, suppress):
"""
Hooks a single-step hotkey (e.g. 'shift+a').
"""
container = _listener.blocking_hotkeys if suppress else _listener.nonblocking_hotkeys
# Register the scan codes of every possible combination of
... |
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').
- `... |
Whenever the hotkey `src` is pressed, suppress it and send
`dst` instead.
Example:
remap('alt+w', 'ctrl+up')
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... |
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_modi... |
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`, alternat... |
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 text integrity, all currently pressed keys are released before
the text ... |
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 hotke... |
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 modifier keys first, in a standardized order;... |
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()
unh... |
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 e... |
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"
def read_hotkey(suppress=True):
"""
Similar to `read_key()`, but blocks until the user p... |
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.
... |
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.
def start_recording(recorded_events_queue=None):
"""
Starts recording all keyboard events into a glo... |
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.')
... |
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 function.
Note: for more details on the keyboard 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()`.
Note: the current keyboard state is cleared at the beginning and restored at
the end of the function.
def play(event... |
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. E.g. 'pet'.
- `callback` is an argument-less function to be invoked each time the word
is ty... |
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 sending backspace events.
- `match_suffix` defines if endings of words should also be checked i... |
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
events by suppressing and re-emitting; and blocked ... |
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 vi... |
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 processed until the Windows messages are pumpe... |
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
... |
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... |
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 `... |
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
release... |
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,)
... |
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, (),... |
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`.
def record(button=RIGHT, target_types=(DOWN,)):
"""
Records... |
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 parameters `include_*` define if events of that type should be inluded
in the replay or ignored.
def play(events... |
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 ... |
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... |
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(
... |
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(
... |
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,
Q... |
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 Eve... |
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 ``modifie... |
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... |
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_(
... |
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.kCGSessionEvent... |
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):]
# Du... |
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 c... |
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.... |
(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 def... |
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 reporte... |
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 ... |
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_c... |
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.
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 pat... |
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:
... |
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[d... |
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/'),
('DA... |
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 Pytho... |
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 from the original distribution. Any such finders need to be
cleared si... |
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 sub-path entries are included as well, i.e. those
corresponding to zip arc... |
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 exec... |
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
... |
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
def get_win_launcher(type):
"""
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
... |
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.l... |
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:
... |
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() + ".... |
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'):
... |
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:
attr... |
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]
... |
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 = []
... |
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' + s... |
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... |
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... |
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... |
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 m... |
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... |
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_h... |
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 lau... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.