coalib.misc package¶
Submodules¶
coalib.misc.BuildManPage module¶
-
class
coalib.misc.BuildManPage.
BuildManPage
(dist)¶ Bases:
distutils.cmd.Command
Add a build_manpage command to your setup.py. To use this Command class add a command to call this class:
# For setuptools setup( entry_points={ "distutils.commands": [ "build_manpage = coalib.misc.BuildManPage:BuildManPage" ] } ) # For distutils from coalib.misc.BuildManPage import BuildManPage setup( cmdclass={'build_manpage': BuildManPage} )
You can then use the following setup command to produce a man page:
$ python setup.py build_manpage --output=coala.1 --parser=coalib.parsing.DefaultArgParser:default_arg_parser
If automatically want to build the man page every time you invoke your build, add to your
`setup.cfg`
the following:[build_manpage] output = <appname>.1 parser = <path_to_your_parser>
-
finalize_options
()¶
-
initialize_options
()¶
-
run
()¶
-
user_options
= [('output=', 'O', 'output file'), ('parser=', None, 'module path to an ArgumentParser instance(e.g. mymod:func, where func is a method or function which returnan arparse.ArgumentParser instance.')]¶
-
coalib.misc.Constants module¶
coalib.misc.ContextManagers module¶
-
coalib.misc.ContextManagers.
make_temp
(suffix='', prefix='tmp', dir=None)¶ Creates a temporary file with a closed stream and deletes it when done.
Returns: A contextmanager retrieving the file path.
-
coalib.misc.ContextManagers.
prepare_file
(lines, filename, force_linebreaks=True, create_tempfile=True, tempfile_kwargs={})¶ Can create a temporary file (if filename is None) with the lines. Can also add a trailing newline to each line specified if needed.
Parameters: - lines – The lines from the file. (list or tuple of strings)
- filename – The filename to be prepared.
- force_linebreaks – Whether to append newlines at each line if needed.
- create_tempfile – Whether to save lines in tempfile if needed.
- tempfile_kwargs – Kwargs passed to tempfile.mkstemp().
-
coalib.misc.ContextManagers.
replace_stderr
(replacement)¶ Replaces stderr with the replacement, yields back to the caller and then reverts everything back.
-
coalib.misc.ContextManagers.
replace_stdout
(replacement)¶ Replaces stdout with the replacement, yields back to the caller and then reverts everything back.
-
coalib.misc.ContextManagers.
retrieve_stderr
()¶ Yields a StringIO object from which one can read everything that was printed to stderr. (It won’t be printed to the real stderr!)
Example usage:
- with retrieve_stderr() as stderr:
- print(“something”) # Won’t print to the console what_was_printed = stderr.getvalue() # Save the value
-
coalib.misc.ContextManagers.
retrieve_stdout
()¶ Yields a StringIO object from which one can read everything that was printed to stdout. (It won’t be printed to the real stdout!)
Example usage:
- with retrieve_stdout() as stdout:
- print(“something”) # Won’t print to the console what_was_printed = stdout.getvalue() # Save the value
-
coalib.misc.ContextManagers.
simulate_console_inputs
(*inputs)¶ Does some magic to simulate the given inputs to any calls to the input builtin. This yields back an InputGenerator object so you can check which input was already used and append any additional inputs you want. Example:
- with simulate_console_inputs(0, 1, 2) as generator:
- assert(input() == 0) assert(generator.last_input == 0) generator.inputs.append(3) assert(input() == 1) assert(input() == 2) assert(input() == 3) assert(generator.last_input == 3)
Parameters: inputs – Any inputs to simulate. Raises: ValueError – Raised when was asked for more input but there’s no more provided.
-
coalib.misc.ContextManagers.
subprocess_timeout
(sub_process, seconds, kill_pg=False)¶ Kill subprocess if the sub process takes more the than the timeout.
Parameters: - sub_process – The sub process to run.
- seconds – The number of seconds to allow the test to run for. If set to 0 or a negative value, it waits indefinitely. Floats can be used to specify units smaller than seconds.
- kill_pg – Boolean whether to kill the process group or only this process. (not applicable for windows)
-
coalib.misc.ContextManagers.
suppress_stdout
()¶ Suppresses everything going to stdout.
coalib.misc.Decorators module¶
-
coalib.misc.Decorators.
arguments_to_lists
(function)¶ Decorator for a function that converts all arguments to lists.
Parameters: function – target function Returns: target function with only lists as parameters
-
coalib.misc.Decorators.
enforce_signature
(function)¶ Enforces the signature of the function by throwing TypeError’s if invalid arguments are provided. The return value is not checked.
You can annotate any parameter of your function with the desired type or a tuple of allowed types. If you annotate the function with a value, this value only will be allowed (useful especially for None). Example:
>>> @enforce_signature ... def test(arg: bool, another: (int, None)): ... pass ... >>> test(True, 5) >>> test(True, None)
Any string value for any parameter e.g. would then trigger a TypeError.
Parameters: function – The function to check.
-
coalib.misc.Decorators.
generate_eq
(*members)¶ Decorator that generates equality and inequality operators for the decorated class. The given members as well as the type of self and other will be taken into account.
Note that this decorator modifies the given class in place!
Parameters: members – A list of members to compare for equality.
-
coalib.misc.Decorators.
generate_ordering
(*members)¶ Decorator that generates ordering operators for the decorated class based on the given member names. All ordering except equality functions will raise a TypeError when a comparison with an unrelated class is attempted. (Comparisons with child classes will thus work fine with the capabilities of the base class as python will choose the base classes comparison operator in that case.)
Note that this decorator modifies the given class in place!
Parameters: members – A list of members to compare, ordered from high priority to low. I.e. if the first member is equal the second will be taken for comparison and so on. If a member is None it is considered smaller than any other value except None.
-
coalib.misc.Decorators.
generate_repr
(*members)¶ Decorator that binds an auto-generated __repr__() function to a class.
The generated __repr__() function prints in following format: <ClassName object(field1=1, field2=’A string’, field3=[1, 2, 3]) at 0xAAAA>
Note that this decorator modifies the given class in place!
Parameters: members –
An iterable of member names to include into the representation-string. Providing no members yields to inclusion of all member variables and properties in alphabetical order (except if they start with an underscore).
To control the representation of each member, you can also pass a tuple where the first element contains the member to print and the second one the representation function (which defaults to the built-in repr()). Using None as representation function is the same as using repr().
Supported members are fields/variables, properties and getter-like functions (functions that accept no arguments).
Raises: - ValueError – Raised when the passed (member, repr-function)-tuples have not a length of 2.
- AttributeError – Raised when a given member/attribute was not found in class.
- TypeError – Raised when a provided member is a bound method that is not a getter-like function (means it must accept no parameters).
Returns: The class armed with an auto-generated __repr__ function.
-
coalib.misc.Decorators.
get_public_members
(obj)¶ Retrieves a dictionary of member-like objects (members or properties) that are publicly exposed.
Parameters: obj – The object to probe. Returns: A dictionary with objects as keys and its attributes as values.
-
coalib.misc.Decorators.
yield_once
(iterator)¶ Decorator to make an iterator yield each result only once.
Parameters: iterator – Any iterator Returns: An iterator that yields every result only once at most.
coalib.misc.DictUtilities module¶
-
coalib.misc.DictUtilities.
add_pair_to_dict
(key, value, dictionary)¶ Add (key, value) pair to the dictionary. The value is added to a list of values for the key.
-
coalib.misc.DictUtilities.
inverse_dicts
(*dicts)¶ Inverts the dicts, e.g. {1: 2, 3: 4} and {2: 3, 4: 4} will be inverted {2: [1, 2], 4: [3, 4]}. This also handles dictionaries with Iterable items as values e.g. {1: [1, 2, 3], 2: [3, 4, 5]} and {2: [1], 3: [2], 4: [3, 4]} will be inverted to {1: [1, 2], 2: [1, 3], 3: [1, 2, 4], 4: [2, 4], 5: [2]}. No order is preserved.
Parameters: dicts – The dictionaries to invert. Returns: The inversed dictionary which merges all dictionaries into one.
-
coalib.misc.DictUtilities.
update_ordered_dict_key
(dictionary, old_key, new_key)¶
coalib.misc.MutableValue module¶
-
class
coalib.misc.MutableValue.
MutableValue
(val=None)¶ Bases:
object
coalib.misc.Shell module¶
-
coalib.misc.Shell.
escape_path_argument
(path, shell='cmd')¶ Makes a raw path ready for using as parameter in a shell command (escapes illegal characters, surrounds with quotes etc.).
Parameters: - path – The path to make ready for shell.
- shell – The shell platform to escape the path argument for. Possible values are “sh”, “powershell”, and “cmd” (others will be ignored and return the given path without modification).
Returns: The escaped path argument.
-
coalib.misc.Shell.
get_shell_type
()¶ Finds the current shell type based on the outputs of common pre-defined variables in them. This is useful to identify which sort of escaping is required for strings.
Returns: The shell type. This can be either “powershell” if Windows Powershell is detected, “cmd” if command prompt is been detected or “sh” if it’s neither of these.
-
coalib.misc.Shell.
prepare_string_argument
(string, shell='cmd')¶ Prepares a string argument for being passed as a parameter on shell.
On sh this function effectively encloses the given string with quotes (either ‘’ or “”, depending on content).
Parameters: - string – The string to prepare for shell.
- shell – The shell platform to prepare string argument for. If it is not “sh” it will be ignored and return the given string without modification.
Returns: The shell-prepared string.
-
coalib.misc.Shell.
run_interactive_shell_command
(command, **kwargs)¶ Runs a command in shell and provides stdout, stderr and stdin streams.
This function creates a context manager that sets up the process, returns to caller, closes streams and waits for process to exit on leaving.
The process is opened in universal_newlines mode.
Parameters: - command – The command to run on shell.
- kwargs – Additional keyword arguments to pass to subprocess.Popen that is used to spawn the process (except shell, stdout, stderr, stdin and universal_newlines, a TypeError is raised then).
Returns: A context manager yielding the process started from the command.
-
coalib.misc.Shell.
run_shell_command
(command, stdin=None, **kwargs)¶ Runs a command in shell and returns the read stdout and stderr data.
This function waits for the process to exit.
Parameters: - command – The command to run on shell.
- stdin – Initial input to send to the process.
- kwargs – Additional keyword arguments to pass to subprocess.Popen that is used to spawn the process (except shell, stdout, stderr, stdin and universal_newlines, a TypeError is raised then).
Returns: A tuple with (stdoutstring, stderrstring).
coalib.misc.StringConverter module¶
-
class
coalib.misc.StringConverter.
StringConverter
(value, strip_whitespaces=True, list_delimiters=None, dict_delimiter=':', remove_empty_iter_elements=True)¶ Bases:
object
Converts strings to other things as needed. If you need some kind of string conversion that is not implemented here, consider adding it so everyone gets something out of it.
-
keys
()¶
-
value
¶
-