text stringlengths 81 112k |
|---|
This closes the connection with the child application. Note that
calling close() more than once is valid. This emulates standard Python
behavior with files. Set force to True if you want to make sure that
the child is terminated (SIGKILL is sent if the child ignores SIGHUP
and SIGINT).
... |
This returns the terminal echo mode. This returns True if echo is
on or False if echo is off. Child applications that are expecting you
to enter a password often set ECHO False. See waitnoecho().
Not supported on platforms where ``isatty()`` returns False.
def getecho(self):
'''This re... |
This sets the terminal echo mode on or off. Note that anything the
child sent before the echo will be lost, so you should be sure that
your input buffer is empty before you call setecho(). For example, the
following will work as expected::
p = pexpect.spawn('cat') # Echo is on by de... |
Read and return at most ``size`` bytes from the pty.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
Unlike Pexpect's ``read_nonblocking`` method, this doesn't try to deal
with the vagaries of EOF on platforms that do strange things, li... |
Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Rai... |
Write bytes to the pseudoterminal.
Returns the number of bytes written.
def write(self, s, flush=True):
"""Write bytes to the pseudoterminal.
Returns the number of bytes written.
"""
return self._writeb(s, flush=flush) |
Helper method that wraps send() with mnemonic access for sending control
character to the child (such as Ctrl-C or Ctrl-D). For example, to send
Ctrl-G (ASCII 7, bell, '\a')::
child.sendcontrol('g')
See also, sendintr() and sendeof().
def sendcontrol(self, char):
'''Helpe... |
This forces a child process to terminate. It starts nicely with
SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
returns True if the child was terminated. This returns False if the
child could not be terminated.
def terminate(self, force=False):
'''This forces a child... |
This waits until the child exits. This is a blocking call. This will
not read any data from the child, so this will block forever if the
child has unread output and has terminated. In other words, the child
may have printed output then called exit(), but, the child is
technically still a... |
This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
SECONDS for Solaris to... |
Send the given signal to the child application.
In keeping with UNIX tradition it has a misleading name. It does not
necessarily kill the child unless you send the right signal. See the
:mod:`signal` module for constants representing signal numbers.
def kill(self, sig):
"""Send the giv... |
Read at most ``size`` bytes from the pty, return them as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
The size argument still refers to bytes, not unicode code points.
def read(self, size=1024):
"""Read at most ``size`` bytes from ... |
Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Rai... |
Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written.
def write(self, s):
"""Write the unicode string ``s`` to the pseudoterminal.
Returns the number of bytes written.
"""
b = s.encode(self.encoding)
return super(PtyProcessUnicode, ... |
Build an instance from a requirement.
def from_requirement(cls, provider, requirement, parent):
"""Build an instance from a requirement.
"""
candidates = provider.find_matches(requirement)
if not candidates:
raise NoVersionsAvailable(requirement, parent)
return cls(
... |
Build a new instance from this and a new requirement.
def merged_with(self, provider, requirement, parent):
"""Build a new instance from this and a new requirement.
"""
infos = list(self.information)
infos.append(RequirementInformation(requirement, parent))
candidates = [
... |
Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
def _push_new_state(self):
"""Push a new state into history.
This new state will be used to hold resolution results of the next
coming round.
"""
try... |
Take a collection of constraints, spit out the resolution result.
The return value is a representation to the final resolution result. It
is a tuple subclass with two public members:
* `mapping`: A dict of resolved candidates. Each key is an identifier
of a requirement (as returned... |
Remove the "extra == ..." operands from the list.
This is not a comprehensive implementation, but relies on an important
characteristic of metadata generation: The "extra == ..." operand is always
associated with an "and" operator. This means that we can simply remove the
operand and the "and" operator... |
Build a new marker without the `extra == ...` part.
The implementation relies very deep into packaging's internals, but I don't
have a better way now (except implementing the whole thing myself).
This could return `None` if the `extra == ...` part is the only one in the
input marker.
def get_without_... |
Collect "extra == ..." operands from a marker.
Returns a list of str. Each str is a speficied extra in this marker.
def get_contained_extras(marker):
"""Collect "extra == ..." operands from a marker.
Returns a list of str. Each str is a speficied extra in this marker.
"""
if not marker:
r... |
Check whehter a marker contains an "extra == ..." operand.
def contains_extra(marker):
"""Check whehter a marker contains an "extra == ..." operand.
"""
if not marker:
return False
marker = Marker(str(marker))
return _markers_contains_extra(marker._markers) |
Return any errors which have occurred.
def get_errors(self):
"""
Return any errors which have occurred.
"""
result = []
while not self.errors.empty(): # pragma: no cover
try:
e = self.errors.get(False)
result.append(e)
exc... |
For a given project, get a dictionary mapping available versions to Distribution
instances.
This calls _get_project to do all the work, and just implements a caching layer on top.
def get_project(self, name):
"""
For a given project, get a dictionary mapping available versions to Distr... |
Give an url a score which can be used to choose preferred URLs
for a given project release.
def score_url(self, url):
"""
Give an url a score which can be used to choose preferred URLs
for a given project release.
"""
t = urlparse(url)
basename = posixpath.basena... |
Choose one of two URLs where both are candidates for distribution
archives for the same version of a distribution (for example,
.tar.gz vs. zip).
The current implementation favours https:// URLs over http://, archives
from PyPI over those from other locations, wheel compatibility (if a
... |
Get a digest from a dictionary by looking at keys of the form
'algo_digest'.
Returns a 2-tuple (algo, digest) if found, else None. Currently
looks only for SHA256, then MD5.
def _get_digest(self, info):
"""
Get a digest from a dictionary by looking at keys of the form
'... |
Return the URLs of all the links on a page together with information
about their "rel" attribute, for determining which ones to treat as
downloads and which ones to queue for further scraping.
def links(self):
"""
Return the URLs of all the links on a page together with information
... |
Threads are created only when get_project is called, and terminate
before it returns. They are there primarily to parallelise I/O (i.e.
fetching web pages).
def _prepare_threads(self):
"""
Threads are created only when get_project is called, and terminate
before it returns. They... |
Tell all the threads to terminate (by sending a sentinel value) and
wait for them to do so.
def _wait_threads(self):
"""
Tell all the threads to terminate (by sending a sentinel value) and
wait for them to do so.
"""
# Note that you need two loops, since you can't say wh... |
See if an URL is a suitable download for a project.
If it is, register information in the result dictionary (for
_get_project) about the specific version it's for.
Note that the return value isn't actually used other than as a boolean
value.
def _process_download(self, url):
"... |
Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scraping.
def _should_queue(self, link, referrer, rel):
"""
Determine whether a link URL from a referring page and with a
particular "rel" attribute should be queued for scrapin... |
Get a URL to fetch from the work queue, get the HTML page, examine its
links for download candidates and candidates for further scraping.
This is a handy method to run in a thread.
def _fetch(self):
"""
Get a URL to fetch from the work queue, get the HTML page, examine its
link... |
Return all the distribution names known to this locator.
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
page = self.get_page(self.base_url)
if not page:
raise DistlibException('Unable to get %... |
Return all the distribution names known to this locator.
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
for root, dirs, files in os.walk(self.base_dir):
for fn in files:
if self.should... |
Return all the distribution names known to this locator.
def get_distribution_names(self):
"""
Return all the distribution names known to this locator.
"""
result = set()
for locator in self.locators:
try:
result |= locator.get_distribution_names()
... |
Add a distribution to the finder. This will update internal information
about who provides what.
:param dist: The distribution to add.
def add_distribution(self, dist):
"""
Add a distribution to the finder. This will update internal information
about who provides what.
:... |
Remove a distribution from the finder. This will update internal
information about who provides what.
:param dist: The distribution to remove.
def remove_distribution(self, dist):
"""
Remove a distribution from the finder. This will update internal
information about who provides... |
Get a version matcher for a requirement.
:param reqt: The requirement
:type reqt: str
:return: A version matcher (an instance of
:class:`distlib.version.Matcher`).
def get_matcher(self, reqt):
"""
Get a version matcher for a requirement.
:param reqt: The... |
Find the distributions which can fulfill a requirement.
:param reqt: The requirement.
:type reqt: str
:return: A set of distribution which can fulfill the requirement.
def find_providers(self, reqt):
"""
Find the distributions which can fulfill a requirement.
:param r... |
Attempt to replace one provider with another. This is typically used
when resolving dependencies from multiple sources, e.g. A requires
(B >= 1.0) while C requires (B >= 1.1).
For successful replacement, ``provider`` must meet all the requirements
which ``other`` fulfills.
:par... |
Find a distribution and all distributions it depends on.
:param requirement: The requirement specifying the distribution to
find, or a Distribution instance.
:param meta_extras: A list of meta extras such as :test:, :build: and
so on.
:par... |
Run in a thread to move output from a pipe to a queue.
def _read_incoming(self):
"""Run in a thread to move output from a pipe to a queue."""
fileno = self.proc.stdout.fileno()
while 1:
buf = b''
try:
buf = os.read(fileno, 1024)
except OSError... |
Send data to the subprocess' stdin.
Returns the number of bytes written.
def send(self, s):
'''Send data to the subprocess' stdin.
Returns the number of bytes written.
'''
s = self._coerce_send_string(s)
self._log(s, 'send')
b = self._encoder.encode(s, final=F... |
Wraps send(), sending string ``s`` to child process, with os.linesep
automatically appended. Returns number of bytes written.
def sendline(self, s=''):
'''Wraps send(), sending string ``s`` to child process, with os.linesep
automatically appended. Returns number of bytes written. '''
n... |
Wait for the subprocess to finish.
Returns the exit code.
def wait(self):
'''Wait for the subprocess to finish.
Returns the exit code.
'''
status = self.proc.wait()
if status >= 0:
self.exitstatus = status
self.signalstatus = None
else:
... |
Sends a Unix signal to the subprocess.
Use constants from the :mod:`signal` module to specify which signal.
def kill(self, sig):
'''Sends a Unix signal to the subprocess.
Use constants from the :mod:`signal` module to specify which signal.
'''
if sys.platform == 'win32':
... |
Like `mkdir`, but does not raise an exception if the
directory already exists.
def mkdir_p(*args, **kwargs):
"""Like `mkdir`, but does not raise an exception if the
directory already exists.
"""
try:
return os.mkdir(*args, **kwargs)
except OSError as exc:
if exc.errno != errno.E... |
Attach a regular expression pattern matcher to a custom type converter
function.
This annotates the type converter with the :attr:`pattern` attribute.
EXAMPLE:
>>> import parse
>>> @parse.with_pattern(r"\d+")
... def parse_number(text):
... return int(text)
is equi... |
Convert a string to an integer.
The string may start with a sign.
It may be of a base other than 10.
If may start with a base indicator, 0#nnnn, which we assume should
override the specified base.
It may also have other non-numeric characters that we can ignore.
def int_convert(base):
'''Co... |
Convert the incoming string containing some date / time info into a
datetime instance.
def date_convert(string, match, ymd=None, mdy=None, dmy=None,
d_m_y=None, hms=None, am=None, tz=None, mm=None, dd=None):
'''Convert the incoming string containing some date / time info into a
datetime instance.
... |
Pull apart the format [[fill]align][0][width][.precision][type]
def extract_format(format, extra_types):
'''Pull apart the format [[fill]align][0][width][.precision][type]
'''
fill = align = None
if format[0] in '<>=^':
align = format[0]
format = format[1:]
elif len(format) > 1 and ... |
Using "format" attempt to pull values from "string".
The format must match the string contents exactly. If the value
you're looking for is instead just a part of the string use
search().
If ``evaluate_result`` is True the return value will be an Result instance with two attributes:
.fixed - tupl... |
Search "string" for the first occurrence of "format".
The format may occur anywhere within the string. If
instead you wish for the format to exactly match the string
use parse().
Optionally start the search at "pos" character index and limit the search
to a maximum index of endpos - equivalent to ... |
Match my format to the string exactly.
Return a Result or Match instance or None if there's no match.
def parse(self, string, evaluate_result=True):
'''Match my format to the string exactly.
Return a Result or Match instance or None if there's no match.
'''
m = self._match_re.... |
Search the string for my format.
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
If the ``evaluate_result`` argument is set to ``False`` a
Match instance is returned instead of the a... |
Search "string" for all occurrences of "format".
Optionally start the search at "pos" character index and limit the
search to a maximum index of endpos - equivalent to
search(string[:endpos]).
Returns an iterator that holds Result or Match instances for each format match
found.... |
Generate a Result instance for the given regex match object
def evaluate_result(self, m):
'''Generate a Result instance for the given regex match object'''
# ok, figure the fixed fields we've pulled out and type convert them
fixed_fields = list(m.groups())
for n in self._fixed_fields:
... |
Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile.
def install(
ctx,
state,
**kwargs
):
"""Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile."""
from ..core impo... |
Un-installs a provided package and removes it from Pipfile.
def uninstall(
ctx,
state,
all_dev=False,
all=False,
**kwargs
):
"""Un-installs a provided package and removes it from Pipfile."""
from ..core import do_uninstall
retcode = do_uninstall(
packages=state.installstate.pack... |
Generates Pipfile.lock.
def lock(
ctx,
state,
**kwargs
):
"""Generates Pipfile.lock."""
from ..core import ensure_project, do_init, do_lock
# Ensure that virtualenv is available.
ensure_project(three=state.three, python=state.python, pypi_mirror=state.pypi_mirror)
if state.installstate... |
Spawns a shell within the virtualenv.
def shell(
state,
fancy=False,
shell_args=None,
anyway=False,
):
"""Spawns a shell within the virtualenv."""
from ..core import load_dot_env, do_shell
# Prevent user from activating nested environments.
if "PIPENV_ACTIVE" in os.environ:
# I... |
Spawns a command installed into the virtualenv.
def run(state, command, args):
"""Spawns a command installed into the virtualenv."""
from ..core import do_run
do_run(
command=command, args=args, three=state.three, python=state.python, pypi_mirror=state.pypi_mirror
) |
Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile.
def check(
state,
unused=False,
style=False,
ignore=None,
args=None,
**kwargs
):
"""Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile."""
from ..core import do_check
... |
Runs lock, then sync.
def update(
ctx,
state,
bare=False,
dry_run=None,
outdated=False,
**kwargs
):
"""Runs lock, then sync."""
from ..core import (
ensure_project,
do_outdated,
do_lock,
do_sync,
project,
)
ensure_project(three=state.thre... |
Displays currently-installed dependency graph information.
def graph(bare=False, json=False, json_tree=False, reverse=False):
"""Displays currently-installed dependency graph information."""
from ..core import do_graph
do_graph(bare=bare, json=json, json_tree=json_tree, reverse=reverse) |
View a given module in your editor.
This uses the EDITOR environment variable. You can temporarily override it,
for example:
EDITOR=atom pipenv open requests
def run_open(state, module, *args, **kwargs):
"""View a given module in your editor.
This uses the EDITOR environment variable. You ca... |
Installs all packages specified in Pipfile.lock.
def sync(
ctx,
state,
bare=False,
user=False,
unused=False,
**kwargs
):
"""Installs all packages specified in Pipfile.lock."""
from ..core import do_sync
retcode = do_sync(
ctx=ctx,
dev=state.installstate.dev,
... |
Uninstalls all packages not specified in Pipfile.lock.
def clean(ctx, state, dry_run=False, bare=False, user=False):
"""Uninstalls all packages not specified in Pipfile.lock."""
from ..core import do_clean
do_clean(ctx=ctx, three=state.three, python=state.python, dry_run=dry_run,
system=state.... |
This function returns either U+FFFD or the character based on the
decimal or hexadecimal representation. It also discards ";" if present.
If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.
def consumeNumberEntity(self, isHex):
"""This function returns either U... |
This method is a generic handler for emitting the tags. It also sets
the state to "data" because that's what's needed after a token has been
emitted.
def emitCurrentToken(self):
"""This method is a generic handler for emitting the tags. It also sets
the state to "data" because that's wh... |
Converts a list of distributions into a PackageSet.
def create_package_set_from_installed(**kwargs):
# type: (**Any) -> Tuple[PackageSet, bool]
"""Converts a list of distributions into a PackageSet.
"""
# Default to using all packages installed on the system
if kwargs == {}:
kwargs = {"loca... |
Check if a package set is consistent
If should_ignore is passed, it should be a callable that takes a
package name and returns a boolean.
def check_package_set(package_set, should_ignore=None):
# type: (PackageSet, Optional[Callable[[str], bool]]) -> CheckResult
"""Check if a package set is consistent... |
For checking if the dependency graph would be consistent after \
installing given requirements
def check_install_conflicts(to_install):
# type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult]
"""For checking if the dependency graph would be consistent after \
installing given requirements
... |
Computes the version of packages after installing to_install.
def _simulate_installation_of(to_install, package_set):
# type: (List[InstallRequirement], PackageSet) -> Set[str]
"""Computes the version of packages after installing to_install.
"""
# Keep track of packages that were installed
install... |
We define three types of bytes:
alphabet: english alphabets [a-zA-Z]
international: international characters [\x80-\xFF]
marker: everything else [^a-zA-Z\x80-\xFF]
The input buffer can be thought to contain a series of words delimited
by markers. This function works to filter al... |
Returns a copy of ``buf`` that retains only the sequences of English
alphabet and high byte characters that are not between <> characters.
Also retains English alphabet and high byte characters immediately
before occurrences of >.
This filter can be applied to all scripts which contain ... |
Join the two paths represented by the respective
(drive, root, parts) tuples. Return a new (drive, root, parts) tuple.
def join_parsed_parts(self, drv, root, parts, drv2, root2, parts2):
"""
Join the two paths represented by the respective
(drive, root, parts) tuples. Return a new (dr... |
Iterate over all child paths of `parent_path` matched by this
selector. This can contain parent_path itself.
def select_from(self, parent_path):
"""Iterate over all child paths of `parent_path` matched by this
selector. This can contain parent_path itself."""
path_cls = type(parent_pa... |
Return the string representation of the path with forward (/)
slashes.
def as_posix(self):
"""Return the string representation of the path with forward (/)
slashes."""
f = self._flavour
return str(self).replace(f.sep, '/') |
The final path component, if any.
def name(self):
"""The final path component, if any."""
parts = self._parts
if len(parts) == (1 if (self._drv or self._root) else 0):
return ''
return parts[-1] |
The final component's last suffix, if any.
def suffix(self):
"""The final component's last suffix, if any."""
name = self.name
i = name.rfind('.')
if 0 < i < len(name) - 1:
return name[i:]
else:
return '' |
A list of the final component's suffixes, if any.
def suffixes(self):
"""A list of the final component's suffixes, if any."""
name = self.name
if name.endswith('.'):
return []
name = name.lstrip('.')
return ['.' + suffix for suffix in name.split('.')[1:]] |
The final path component, minus its last suffix.
def stem(self):
"""The final path component, minus its last suffix."""
name = self.name
i = name.rfind('.')
if 0 < i < len(name) - 1:
return name[:i]
else:
return name |
Return a new path with the file name changed.
def with_name(self, name):
"""Return a new path with the file name changed."""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
drv, root, parts = self._flavour.parse_parts((name,))
if (not name or name[-1] in... |
Return a new path with the file suffix changed (or added, if
none).
def with_suffix(self, suffix):
"""Return a new path with the file suffix changed (or added, if
none).
"""
# XXX if suffix is None, should the current suffix be removed?
f = self._flavour
if f.sep... |
An object providing sequence-like access to the
components in the filesystem path.
def parts(self):
"""An object providing sequence-like access to the
components in the filesystem path."""
# We cache the tuple to avoid building a new one each time .parts
# is accessed. XXX is t... |
The logical parent of the path.
def parent(self):
"""The logical parent of the path."""
drv = self._drv
root = self._root
parts = self._parts
if len(parts) == 1 and (drv or root):
return self
return self._from_parsed_parts(drv, root, parts[:-1]) |
True if the path is absolute (has both a root and, if applicable,
a drive).
def is_absolute(self):
"""True if the path is absolute (has both a root and, if applicable,
a drive)."""
if not self._root:
return False
return not self._flavour.has_drv or bool(self._drv) |
Return True if this path matches the given pattern.
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
... |
Open the file pointed by this path and return a file descriptor,
as os.open() does.
def _raw_open(self, flags, mode=0o777):
"""
Open the file pointed by this path and return a file descriptor,
as os.open() does.
"""
if self._closed:
self._raise_closed()
... |
Return whether other_path is the same or not as this file
(as returned by os.path.samefile()).
def samefile(self, other_path):
"""Return whether other_path is the same or not as this file
(as returned by os.path.samefile()).
"""
if hasattr(os.path, "samestat"):
st = ... |
Iterate over the files in this directory. Does not yield any
result for the special paths '.' and '..'.
def iterdir(self):
"""Iterate over the files in this directory. Does not yield any
result for the special paths '.' and '..'.
"""
if self._closed:
self._raise_cl... |
Create this file with the given access mode, if it doesn't exist.
def touch(self, mode=0o666, exist_ok=True):
"""
Create this file with the given access mode, if it doesn't exist.
"""
if self._closed:
self._raise_closed()
if exist_ok:
# First try to bump ... |
Create a new directory at this given path.
def mkdir(self, mode=0o777, parents=False, exist_ok=False):
"""
Create a new directory at this given path.
"""
if self._closed:
self._raise_closed()
def _try_func():
self._accessor.mkdir(self, mode)
def... |
Change the permissions of the path, like os.chmod().
def chmod(self, mode):
"""
Change the permissions of the path, like os.chmod().
"""
if self._closed:
self._raise_closed()
self._accessor.chmod(self, mode) |
Like chmod(), except if the path points to a symlink, the symlink's
permissions are changed, rather than its target's.
def lchmod(self, mode):
"""
Like chmod(), except if the path points to a symlink, the symlink's
permissions are changed, rather than its target's.
"""
i... |
Remove this file or link.
If the path is a directory, use rmdir() instead.
def unlink(self):
"""
Remove this file or link.
If the path is a directory, use rmdir() instead.
"""
if self._closed:
self._raise_closed()
self._accessor.unlink(self) |
Remove this directory. The directory must be empty.
def rmdir(self):
"""
Remove this directory. The directory must be empty.
"""
if self._closed:
self._raise_closed()
self._accessor.rmdir(self) |
Like stat(), except if the path points to a symlink, the symlink's
status information is returned, rather than its target's.
def lstat(self):
"""
Like stat(), except if the path points to a symlink, the symlink's
status information is returned, rather than its target's.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.