INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Extracts the exception line from the input string and marks the location of the exception with a special symbol.
def markInputline( self, markerString = ">!<" ): """Extracts the exception line from the input string, and marks the location of the exception with a special symbol. """ line_str = self.line line_column = self.column - 1 if markerString: line_str = "".join(...
Method to take an exception and translate the Python internal traceback into a list of the pyparsing expressions that caused the exception to be raised.
def explain(exc, depth=16): """ Method to take an exception and translate the Python internal traceback into a list of the pyparsing expressions that caused the exception to be raised. Parameters: - exc - exception raised during parsing (need not be a ParseException, in suppor...
Removes and returns item at specified index ( default = last ). Supports both list and dict semantics for pop (). If passed no argument or an integer argument it will use list semantics and pop tokens from the list of parsed tokens. If passed a non - integer argument ( most likely a string ) it will use dict semantics ...
def pop( self, *args, **kwargs): """ Removes and returns item at specified index (default= ``last``). Supports both ``list`` and ``dict`` semantics for ``pop()``. If passed no argument or an integer argument, it will use ``list`` semantics and pop tokens from the list of parsed t...
Add sequence of elements to end of ParseResults list of elements.
def extend( self, itemseq ): """ Add sequence of elements to end of ParseResults list of elements. Example:: patt = OneOrMore(Word(alphas)) # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): ...
Returns the parse results as a nested list of matching tokens all converted to strings.
def asList( self ): """ Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it i...
Returns the named parse results as a nested dictionary.
def asDict( self ): """ Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parseString('12/31/1999') print(type(resu...
r Returns the results name for this token expression. Useful when several different expressions might match at a particular location.
def getName(self): r""" Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = S...
Diagnostic method for listing out the contents of a: class: ParseResults. Accepts an optional indent argument so that this string can be embedded in a nested display of other data.
def dump(self, indent='', depth=0, full=True): """ Diagnostic method for listing out the contents of a :class:`ParseResults`. Accepts an optional ``indent`` argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums...
Pretty - printer for parsed results as a list using the pprint <https:// docs. python. org/ 3/ library/ pprint. html > _ module. Accepts additional positional or keyword args as defined for pprint. pprint <https:// docs. python. org/ 3/ library/ pprint. html#pprint. pprint > _.
def pprint(self, *args, **kwargs): """ Pretty-printer for parsed results as a list, using the `pprint <https://docs.python.org/3/library/pprint.html>`_ module. Accepts additional positional or keyword args as defined for `pprint.pprint <https://docs.python.org/3/library/pprint.ht...
Make a copy of this: class: ParserElement. Useful for defining different parse actions for the same parsing pattern using copies of the original parse element.
def copy( self ): """ Make a copy of this :class:`ParserElement`. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element. Example:: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) ...
Define name for this expression makes debugging and exception messages clearer.
def setName( self, name ): """ Define name for this expression, makes debugging and exception messages clearer. Example:: Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1) Word(nums).setName("integer").parseString("ABC") #...
Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a * copy * of the original: class: ParserElement object ; this is so that the client can define a basic element such as an integer and reference it in multiple places with different names.
def setResultsName( self, name, listAllMatches=False ): """ Define name for referencing matching tokens as a nested attribute of the returned parse results. NOTE: this returns a *copy* of the original :class:`ParserElement` object; this is so that the client can define a basic el...
Add a boolean predicate function to expression s list of parse actions. See: class: setParseAction for function call signatures. Unlike setParseAction functions passed to addCondition need to return boolean success/ fail of the condition.
def addCondition(self, *fns, **kwargs): """Add a boolean predicate function to expression's list of parse actions. See :class:`setParseAction` for function call signatures. Unlike ``setParseAction``, functions passed to ``addCondition`` need to return boolean success/fail of the condition. ...
Enables packrat parsing which adds memoizing to the parsing logic. Repeated parse attempts at the same string location ( which happens often in many complex grammars ) can immediately return a cached value instead of re - executing parsing/ validating code. Memoizing is done of both valid results and parsing exceptions...
def enablePackrat(cache_size_limit=128): """Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing par...
Execute the parse expression with the given string. This is the main interface to the client code once the complete expression has been built.
def parseString( self, instring, parseAll=False ): """ Execute the parse expression with the given string. This is the main interface to the client code, once the complete expression has been built. If you want the grammar to require that the entire input string be succe...
Another extension to: class: scanString simplifying the access to the tokens found to match the given parse expression. May be called with optional maxMatches argument to clip searching after n matches are found.
def searchString( self, instring, maxMatches=_MAX_INT ): """ Another extension to :class:`scanString`, simplifying the access to the tokens found to match the given parse expression. May be called with optional ``maxMatches`` argument, to clip searching after 'n' matches are found. ...
Generator method to split a string using the given expression as a separator. May be called with optional maxsplit argument to limit the number of splits ; and the optional includeSeparators argument ( default = False ) if the separating matching text should be included in the split results.
def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): """ Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``includeSeparators`` argument (defa...
Overrides the default whitespace chars
def setWhitespaceChars( self, chars ): """ Overrides the default whitespace chars """ self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self
Define expression to be ignored ( e. g. comments ) while doing pattern matching ; may be called repeatedly to define multiple comment or other ignorable patterns.
def ignore( self, other ): """ Define expression to be ignored (e.g., comments) while doing pattern matching; may be called repeatedly, to define multiple comment or other ignorable patterns. Example:: patt = OneOrMore(Word(alphas)) patt.parseString('abl...
Enable display of debugging messages while doing pattern matching.
def setDebugActions( self, startAction, successAction, exceptionAction ): """ Enable display of debugging messages while doing pattern matching. """ self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, ...
Enable display of debugging messages while doing pattern matching. Set flag to True to enable False to disable.
def setDebug( self, flag=True ): """ Enable display of debugging messages while doing pattern matching. Set ``flag`` to True to enable, False to disable. Example:: wd = Word(alphas).setName("alphaword") integer = Word(nums).setName("numword") term = ...
Execute the parse expression on the given file or filename. If a filename is specified ( instead of a file object ) the entire file is opened read and closed before parsing.
def parseFile( self, file_or_filename, parseAll=False ): """ Execute the parse expression on the given file or filename. If a filename is specified (instead of a file object), the entire file is opened, read, and closed before parsing. """ try: file_contents =...
Return Regex with an attached parse action to transform the parsed result as if called using re. sub ( expr repl string ) <https:// docs. python. org/ 3/ library/ re. html#re. sub > _.
def sub(self, repl): """ Return Regex with an attached parse action to transform the parsed result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_. Example:: make_html = Regex(r"(\w+):(.*?):").sub(r"<\1>\2</\1>") ...
Extends leaveWhitespace defined in base class and also invokes leaveWhitespace on all contained expressions.
def leaveWhitespace( self ): """Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on all contained expressions.""" self.skipWhitespace = False self.exprs = [ e.copy() for e in self.exprs ] for e in self.exprs: e.leaveWhitespace...
Helper to create a parse action for converting parsed date string to Python datetime. date
def convertToDate(fmt="%Y-%m-%d"): """ Helper to create a parse action for converting parsed date string to Python datetime.date Params - - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``) Example:: date_expr = pyparsing_common.iso8601_date...
Helper to create a parse action for converting parsed datetime string to Python datetime. datetime
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"): """Helper to create a parse action for converting parsed datetime string to Python datetime.datetime Params - - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%dT%H:%M:%S.%f"``) Example:: dt_exp...
Look for VCS schemes in the URL.
def _match_vcs_scheme(url): # type: (str) -> Optional[str] """Look for VCS schemes in the URL. Returns the matched VCS scheme, or None if there's no match. """ from pipenv.patched.notpip._internal.vcs import VcsSupport for scheme in VcsSupport.schemes: if url.lower().startswith(scheme) ...
Return whether the URL looks like an archive.
def _is_url_like_archive(url): # type: (str) -> bool """Return whether the URL looks like an archive. """ filename = Link(url).filename for bad_ext in ARCHIVE_EXTENSIONS: if filename.endswith(bad_ext): return True return False
Check the Content - Type header to ensure the response contains HTML.
def _ensure_html_header(response): # type: (Response) -> None """Check the Content-Type header to ensure the response contains HTML. Raises `_NotHTML` if the content type is not text/html. """ content_type = response.headers.get("Content-Type", "") if not content_type.lower().startswith("text/h...
Send a HEAD request to the URL and ensure the response contains HTML.
def _ensure_html_response(url, session): # type: (str, PipSession) -> None """Send a HEAD request to the URL, and ensure the response contains HTML. Raises `_NotHTTP` if the URL is not available for a HEAD request, or `_NotHTML` if the content type is not text/html. """ scheme, netloc, path, qu...
Access an HTML page with GET and return the response.
def _get_html_response(url, session): # type: (str, PipSession) -> Response """Access an HTML page with GET, and return the response. This consists of three parts: 1. If the URL looks suspiciously like an archive, send a HEAD first to check the Content-Type is HTML, to avoid downloading a large...
Find the separator s index based on the package s canonical name.
def _find_name_version_sep(egg_info, canonical_name): # type: (str, str) -> int """Find the separator's index based on the package's canonical name. `egg_info` must be an egg info string for the given package, and `canonical_name` must be the package's canonical name. This function is needed since...
Pull the version part out of a string.
def _egg_info_matches(egg_info, canonical_name): # type: (str, str) -> Optional[str] """Pull the version part out of a string. :param egg_info: The string to parse. E.g. foo-2.1 :param canonical_name: The canonicalized name of the package this belongs to. """ try: version_start ...
Determine the HTML document s base URL.
def _determine_base_url(document, page_url): """Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the ...
Determine if we have any encoding information in our headers.
def _get_encoding_from_headers(headers): """Determine if we have any encoding information in our headers. """ if headers and "Content-Type" in headers: content_type, params = cgi.parse_header(headers["Content-Type"]) if "charset" in params: return params['charset'] return Non...
Function used to generate link sort key for link tuples. The greater the return value the more preferred it is. If not finding wheels then sorted by version only. If finding wheels then the sort order is by version then: 1. existing installs 2. wheels ordered via Wheel. support_index_min ( self. valid_tags ) 3. source ...
def _candidate_sort_key(self, candidate, ignore_compatibility=True): # type: (InstallationCandidate, bool) -> CandidateSortingKey """ Function used to generate link sort key for link tuples. The greater the return value, the more preferred it is. If not finding wheels, then sorte...
Returns the locations found via self. index_urls
def _get_index_urls_locations(self, project_name): # type: (str) -> List[str] """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): ...
Find all available InstallationCandidate for project_name
def find_all_candidates(self, project_name): # type: (str) -> List[Optional[InstallationCandidate]] """Find all available InstallationCandidate for project_name This checks index_urls and find_links. All versions found are returned as an InstallationCandidate list. See _link_pa...
Try to find a Link matching req
def find_requirement(self, req, upgrade, ignore_compatibility=False): # type: (InstallRequirement, bool, bool) -> Optional[Link] """Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a Link if found, Raises DistributionNotFound or B...
Yields ( page page_url ) from the given locations skipping locations that have errors.
def _get_pages(self, locations, project_name): # type: (Iterable[Link], str) -> Iterable[HTMLPage] """ Yields (page, page_url) from the given locations, skipping locations that have errors. """ seen = set() # type: Set[Link] for location in locations: ...
Return an InstallationCandidate or None
def _link_package_versions(self, link, search, ignore_compatibility=True): # type: (Link, Search, bool) -> Optional[InstallationCandidate] """Return an InstallationCandidate or None""" version = None if link.egg_fragment: egg_info = link.egg_fragment ext = link.ex...
Yields all links in the page
def iter_links(self): # type: () -> Iterable[Link] """Yields all links in the page""" document = html5lib.parse( self.content, transport_encoding=_get_encoding_from_headers(self.headers), namespaceHTMLElements=False, ) base_url = _determine_bas...
This function runs the given command ; waits for it to finish ; then returns all output as a string. STDERR is included in output. If the full path to the command is not given then the path is searched.
def run(command, timeout=30, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, **kwargs): ''' This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in output. If the full path to the command is n...
Deprecated: pass encoding to run () instead.
def runu(command, timeout=30, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, **kwargs): """Deprecated: pass encoding to run() instead. """ kwargs.setdefault('encoding', 'utf-8') return run(command, timeout=timeout, withexitstatus=withexitstatus, ...
Try to look up the process tree via the output of ps.
def get_process_mapping(): """Try to look up the process tree via the output of `ps`. """ output = subprocess.check_output([ 'ps', '-ww', '-o', 'pid=', '-o', 'ppid=', '-o', 'args=', ]) if not isinstance(output, str): output = output.decode(sys.stdout.encoding) processes = {} ...
Build the path URL to use.
def path_url(self): """Build the path URL to use.""" url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return...
Encode parameters in a piece of data.
def _encode_params(data): """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data...
Build the body for a multipart/ form - data request.
def _encode_files(files, data): """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tu...
Properly register a hook.
def register_hook(self, event, hook): """Properly register a hook.""" if event not in self.hooks: raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, '__...
Deregister a previously registered hook. Returns True if the hook existed False if not.
def deregister_hook(self, event, hook): """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False
Prepares the entire request with the given parameters.
def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): """Prepares the entire request with the given parameters.""" self.prepare_method(method) self.prepare_url(url, params) self...
Prepares the given HTTP body data.
def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: ...
Prepare Content - Length header based on request method and body
def prepare_content_length(self, body): """Prepare Content-Length header based on request method and body""" if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked...
Prepares the given HTTP auth data.
def prepare_auth(self, auth, url=''): """Prepares the given HTTP auth data.""" # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: ...
Prepares the given HTTP cookie data.
def prepare_cookies(self, cookies): """Prepares the given HTTP cookie data. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib's design, the header will not be regenerated if it already exists, meaning this function ca...
Prepares the given hooks.
def prepare_hooks(self, hooks): """Prepares the given hooks.""" # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: sel...
True if this Response one of the permanent versions of redirect.
def is_permanent_redirect(self): """True if this Response one of the permanent versions of redirect.""" return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
Content of the response in unicode.
def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of ...
Raises stored: class: HTTPError if one occurred.
def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn'...
Releases the connection back to the pool. Once this method has been called the underlying raw object must not be accessed again.
def close(self): """Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.* """ if not self._content_consumed: self.raw.close() ...
Format an error message for an EnvironmentError
def create_env_error_message(error, show_traceback, using_user_site): """Format an error message for an EnvironmentError It may occur anytime during the execution of the install command. """ parts = [] # Mention the error if we are not going to show a traceback parts.append("Could not install ...
Process IPv6 address literals
def _ipv6_host(host, scheme): """ Process IPv6 address literals """ # httplib doesn't like it when we include brackets in IPv6 addresses # Specifically, if we include brackets but also pass the port then # httplib crazily doubles up the square brackets on the Host header. # Instead, we need...
Get a connection. Will return a pooled connection if one is available.
def _get_conn(self, timeout=None): """ Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and r...
Helper that always returns a: class: urllib3. util. Timeout
def _get_timeout(self, timeout): """ Helper that always returns a :class:`urllib3.util.Timeout` """ if timeout is _Default: return self.timeout.clone() if isinstance(timeout, Timeout): return timeout.clone() else: # User passed us an int/float. This i...
Is the error actually a timeout? Will raise a ReadTimeout or pass
def _raise_timeout(self, err, url, timeout_value): """Is the error actually a timeout? Will raise a ReadTimeout or pass""" if isinstance(err, SocketTimeout): raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # See the above comment about EAGAIN ...
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request so you ll need to specify all the raw details.
def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw): """ Get a connection from the pool and perform...
Prepare the connection for: meth: urllib3. util. ssl_wrap_socket and establish the tunnel if proxy is used.
def _prepare_conn(self, conn): """ Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used. """ if isinstance(conn, VerifiedHTTPSConnection): conn.set_cert(key_file=self.key_file, cert_fi...
Establish tunnel connection early because otherwise httplib would improperly set Host: header to proxy s IP: port.
def _prepare_proxy(self, conn): """ Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy's IP:port. """ conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers) conn.connect()
Rebuilds the base system path and all of the contained finders within it.
def reload_system_path(self): # type: () -> None """ Rebuilds the base system path and all of the contained finders within it. This will re-apply any changes to the environment or any version changes on the system. """ if self._system_path is not None: self....
Find the python version which corresponds most closely to the version requested.
def find_python_version( self, major=None, minor=None, patch=None, pre=None, dev=None, arch=None, name=None ): # type: (Optional[Union[str, int]], Optional[int], Optional[int], Optional[bool], Optional[bool], Optional[str], Optional[str]) -> PathEntry """ Find the python version whic...
Get the shell that the supplied pid or os. getpid () is running in.
def get_shell(pid=None, max_depth=6): """Get the shell that the supplied pid or os.getpid() is running in. """ pid = str(pid or os.getpid()) mapping = _get_process_mapping() login_shell = os.environ.get('SHELL', '') for _ in range(max_depth): try: proc = mapping[pid] ...
Make the given class un - picklable.
def _make_class_unpicklable(cls): """Make the given class un-picklable.""" def _break_on_call_reduce(self, protocol=None): raise TypeError('%r cannot be pickled' % self) cls.__reduce_ex__ = _break_on_call_reduce cls.__module__ = '<unknown>'
Create a new Enum subclass that replaces a collection of global constants
def _convert(cls, name, module, filter, source=None): """ Create a new Enum subclass that replaces a collection of global constants """ # convert all constants from source (or module) that pass filter() to # a new Enum called name, and export the enum and its members back to # module; # also...
Class decorator that ensures only unique members exist in an enumeration.
def unique(enumeration): """Class decorator that ensures only unique members exist in an enumeration.""" duplicates = [] for name, member in enumeration.__members__.items(): if name != member.name: duplicates.append((name, member.name)) if duplicates: duplicate_names = ', '.j...
Convenience method to create a new Enum class.
def _create_(cls, class_name, names=None, module=None, type=None, start=1): """Convenience method to create a new Enum class. `names` can be: * A string containing member names, separated either with spaces or commas. Values are auto-numbered from 1. * An iterable of member ...
Returns the type for creating enum members and the first inherited enum class.
def _get_mixins_(bases): """Returns the type for creating enum members, and the first inherited enum class. bases: the tuple of bases that was given to __new__ """ if not bases or Enum is None: return object, Enum # double check that we are not subclassing...
Returns a Basic Auth string.
def _basic_auth_str(username, password): """Returns a Basic Auth string.""" # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to maintain backward...
Convert the package data into something usable by output_package_listing_columns.
def format_for_columns(pkgs, options): """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", ...
Create a package finder appropriate to this list command.
def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, ...
Build a shebang line. In the simple case ( on Windows or a shebang line which is not too long or contains spaces ) use a simple formulation for the shebang. Otherwise use/ bin/ sh as the executable with a contrived shebang which allows the script to run either under Python or sh using suitable quoting. Thanks to Harald...
def _build_shebang(self, executable, post_interp): """ Build a shebang line. In the simple case (on Windows, or a shebang line which is not too long or contains spaces) use a simple formulation for the shebang. Otherwise, use /bin/sh as the executable, with a contrived shebang wh...
Make a script.
def make(self, specification, options=None): """ Make a script. :param specification: The specification, which is either a valid export entry specification (to make a script from a callable) or a filename (to make a script by ...
Take a list of specifications and make scripts from them: param specifications: A list of specifications.: return: A list of all absolute pathnames written to
def make_multiple(self, specifications, options=None): """ Take a list of specifications and make scripts from them, :param specifications: A list of specifications. :return: A list of all absolute pathnames written to, """ filenames = [] for specification in spec...
Returns a generator that yields file paths under a * directory * matching * patterns * using glob _ syntax ( e. g. *. txt ). Also supports * ignored * patterns.
def iter_find_files(directory, patterns, ignored=None): """Returns a generator that yields file paths under a *directory*, matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also supports *ignored* patterns. Args: directory (str): Path that serves as the root of the search....
Create a: class: FilePerms object from an integer.
def from_int(cls, i): """Create a :class:`FilePerms` object from an integer. >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal FilePerms(user='rw', group='r', other='r') """ i &= FULL_PERMS key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx') part...
Make a new: class: FilePerms object based on the permissions assigned to the file or directory at * path *.
def from_path(cls, path): """Make a new :class:`FilePerms` object based on the permissions assigned to the file or directory at *path*. Args: path (str): Filesystem path of the target file. >>> from os.path import expanduser >>> 'r' in FilePerms.from_path(expanduser...
Called on context manager entry ( the: keyword: with statement ) the setup () method creates the temporary file in the same directory as the destination file.
def setup(self): """Called on context manager entry (the :keyword:`with` statement), the ``setup()`` method creates the temporary file in the same directory as the destination file. ``setup()`` tests for a writable directory with rename permissions early, as the part file may no...
Loads a pipfile from a given path. If none is provided one will try to be found.
def load(pipfile_path=None, inject_env=True): """Loads a pipfile from a given path. If none is provided, one will try to be found. """ if pipfile_path is None: pipfile_path = Pipfile.find() return Pipfile.load(filename=pipfile_path, inject_env=inject_env)
Recursively injects environment variables into TOML values
def inject_environment_variables(self, d): """ Recursively injects environment variables into TOML values """ if not d: return d if isinstance(d, six.string_types): return os.path.expandvars(d) for k, v in d.items(): if isinstance(v, s...
Returns the path of a Pipfile in parent directories.
def find(max_depth=3): """Returns the path of a Pipfile in parent directories.""" i = 0 for c, d, f in walk_up(os.getcwd()): i += 1 if i < max_depth: if 'Pipfile': p = os.path.join(c, 'Pipfile') if os.path.isfile(p)...
Load a Pipfile from a given filename.
def load(klass, filename, inject_env=True): """Load a Pipfile from a given filename.""" p = PipfileParser(filename=filename) pipfile = klass(filename=filename) pipfile.data = p.parse(inject_env=inject_env) return pipfile
Returns the SHA256 of the pipfile s data.
def hash(self): """Returns the SHA256 of the pipfile's data.""" content = json.dumps(self.data, sort_keys=True, separators=(",", ":")) return hashlib.sha256(content.encode("utf8")).hexdigest()
Returns a JSON representation of the Pipfile.
def lock(self): """Returns a JSON representation of the Pipfile.""" data = self.data data['_meta']['hash'] = {"sha256": self.hash} data['_meta']['pipfile-spec'] = 6 return json.dumps(data, indent=4, separators=(',', ': '))
Asserts PEP 508 specifiers.
def assert_requirements(self): """"Asserts PEP 508 specifiers.""" # Support for 508's implementation_version. if hasattr(sys, 'implementation'): implementation_version = format_full_version(sys.implementation.version) else: implementation_version = "0" #...
copy data from file - like object fsrc to file - like object fdst
def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
Copy data from src to dst
def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass ...
Copy mode bits from src to dst
def copymode(src, dst): """Copy mode bits from src to dst""" if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode)
Copy all stat info ( mode bits atime mtime flags ) from src to dst
def copystat(src, dst): """Copy all stat info (mode bits, atime, mtime, flags) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) if hasattr(os, 'chfl...
Copy data and mode bits ( cp src dst ).
def copy(src, dst): """Copy data and mode bits ("cp src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst)
Copy data and all stat info ( cp - p src dst ).
def copy2(src, dst): """Copy data and all stat info ("cp -p src dst"). The destination may be a directory. """ if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst)
Recursively delete a directory tree.
def rmtree(path, ignore_errors=False, onerror=None): """Recursively delete a directory tree. If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is th...