Remaining Modules

env

Simple module that pretty prints the user’s environment variables.

This is actually implemented as an IPython magic but to make it easier to use in a typical Python REPL it’s also implemented here.

The if name == '__main__' is left off so that it can be run directly or sourced.

class pyutil.env.Env(env=None)[source]

Bases: object

Memoize the user’s current environment variable settings.

class pyutil.env.WindowsEnv(admin=False)[source]

Bases: pyutil.env.Env

Windows specific things.

get_registry(self)[source]
pyutil.env.current()[source]

Prints all current environment variables.

env_checks

Run simple checks to ensure that a user’s environment has been set up.

Easier to group similar methods in one mod then have them scattered around.

Below is a generic example of using the public methods to read in user defined configurations.

Example

>>> from env_checks import check_xdg_config_home
>>> if check_xdg_config_home():
    >>> with open('module.conf', 'rt') as f:
        >>> configs = f.readlines()

Matplotlib Env Checks

Mar 08, 2019

Just noticed today the following functions:

try:
    import matplotlib as mpl
except ImportError:
    pass
mpl.get_home()
mpl._get_xdg_cache_dir()
mpl._get_xdg_config_dir()
mpl._get_data_path()

Here’s an interesting way to memoize return values.:

def _logged_cached(fmt, func=None):
    '''
    Decorator that logs a function's return value, and memoizes that value.

    After ::

        @_logged_cached(fmt)
        def func(): ...

    the first call to *func* will log its return value at the DEBUG level using
    %-format string *fmt*, and memoize it; later calls to *func* will directly
    return that value.
    '''
    if func is None:  # Return the actual decorator.
        return functools.partial(_logged_cached, fmt)

    called = False
    ret = None

    @functools.wraps(func)
    def wrapper():
        nonlocal called, ret
        if not called:
            ret = func()
            called = True
            _log.debug(fmt, ret)
        return ret

    return wrapper
pyutil.env_checks.check_xdg_config_home()[source]

Check to see if $XDG_CONFIG_HOME has been defined.

Returns

Return type

Bool

Examples

>>> from env_checks import check_xdg_config_home
>>> if check_xdg_config_home():
    >>> with open('module.conf', 'rt') as f:
        >>> configs = f.readlines()
pyutil.env_checks.check_xdg_config_home_2(conf_file=None)[source]

An implementation of check_xdg_config_home that works with Python2!

Unfortunately the code is quite repetitive as it stands and needs refactoring.

Note

Has not been tested on Python2.

Parameters

conf_file (str, optional) – Path to a configuration file needed by another module.

Returns

user_conf_file – Path to desired user configuration file. Returns None if the file can’t be found.

Return type

str

pyutil.env_checks.env_check(env_var)[source]

Search the current namescope for variable env_var.

Parameters

env_var (str) – Environment variable to search for. Currently case-sensitive.

Yields

i (dict_key) – The environment variable searched for. Env vars are mapped as dicts.

Example

>>> from env_checks import env_check
>>> fzf = list(env_check('fzf'))
[
        '_fzf_orig_completion_awk', '_fzf_orig_completion_cat',
        '_fzf_orig_completion_cd', '_fzf_orig_completion_cp',
        '_fzf_orig_completion_diff', '_fzf_orig_completion_du',
        '_fzf_orig_completion_ftp', '_fzf_orig_completion_grep',
        '_fzf_orig_completion_head', '_fzf_orig_completion_ld',
        '_fzf_orig_completion_less', '_fzf_orig_completion_ln',
        '_fzf_orig_completion_ls', '_fzf_orig_completion_mv',
        '_fzf_orig_completion_pushd', '_fzf_orig_completion_rm',
        '_fzf_orig_completion_rmdir', '_fzf_orig_completion_sed',
        '_fzf_orig_completion_sort', '_fzf_orig_completion_tail',
        '_fzf_orig_completion_tee', '_fzf_orig_completion_telnet',
        '_fzf_orig_completion_uniq', '_fzf_orig_completion_wc'
        ]
pyutil.env_checks.get_home_3()[source]

Return the user’s home directory. Python3 only!

Returns

home – The user’s home directory. Utilizes pathlib so requires Python 3. Returns None if the home directory isn’t found.

Return type

pathlib.Path

pyutil.env_checks.get_script_dir(fobj)[source]

Determine the directory the script is in.

Parameters

fobj (str) – Path to file to check

Returns

Directory the file is in

Return type

str

pyutil.env_checks.get_unix_username()[source]

Get username. Unix only!

Returns

username – User username

Return type

str

pyutil.env_checks.get_username()[source]

More cross-platform implementation of retrieving a username.

This function checks the environment variables LOGNAME, USER, LNAME and USERNAME, in order, and returns the value of the first one which is set to a non-empty string. If none are set, the login name from the password database is returned on systems which support the pwd module, otherwise, an exception is raised.

In general, this function should be preferred over os.getlogin().

itersrc

Iterate over all of the python files in a directory recursively.

Changed in version 0.0.1: Just added a check for python files. This could be useful as a base for a test runner.

pyutil.itersrc.iter_source_code(paths)[source]

Iterate over all Python source files in C{paths}.

Taken with almost no modifications from pyflakes.

This would be a great function to call with os.listdir() output.

Parameters

paths (list) – A list of paths. Directories will be recursed into and any .py files found will be yielded. Any non-directories will be yielded as-is.

Yields

full_path (str) – Absolute path to a python file.

ptags

Create a tags file for Python programs, usable with vi.

Currently uses a regex to create a tags file.

Files to tag

  • functions (even inside other defs or classes)

  • classes

  • filenames

Warns about files it cannot open.

No warnings about duplicate tags.

Snagged from the scripts dir in python3.6-examples.

Todo

Use ipdb and step through while watching the tags var.

Otherwise add in PEP 257 compliant params. Try different styles and see what you like.

pyutil.ptags.main()[source]

Handle CLAs and work with writing the tags file.

pyutil.ptags.treat_file(filename)[source]

Find usable matches for tags file.

Parameters

filename (path-like object) – File to generate tags from.

Returns

None

Return type

None

strip_space

Strip only trailing whitespace from a file.

Leading whitespace is significant in Python so don’t touch it.

pyutil.strip_space.backup(src)[source]

Backs up a file before doing anything.

Parameters

src (file) – File to strip trailing whitespace from. Backed up before anything.

pyutil.strip_space.main()[source]

Dispatch the strip_space function.

pyutil.strip_space.strip_space(src=<_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>)[source]

Strip all trailing whitespace out of a file.

Assumes a plaintext file. Uses sys.stdin if no argument provided.

Parameters

src (str) – File to strip trailing whitespace from. Backed up before anything.

sys_checks

Module to check a user is utilizing the proper version of python.

Even outside of the 2 to 3 incompatibilities, the standard library introduces new modules often enough that it’s useful to check what version oof Python is being run.

Assumes: All functions are imported as the module will immediately exit if directly executed.

If nothing else this is a lesson in how painful it becomes to maintain nonsense names.

Expanding to Paths

This module is admittedly quite limited if we only check sys.executable.

Let’s do some general file checking with pathlib. This module itself was added to the standard library recently, and as a result, we’ll import it with a try statement.

pyutil.sys_checks.is_file(file_obj)[source]

Check a file exists on the system.

Examples

>>> from pyutil.sys_checks import is_file
>>> if is_file('path/to/file'):
    >>> pass
pyutil.sys_checks.py_gt_exit(min_py_version)[source]

Check a user’s python version is higher than some floor value.

For example, the argparse was only introduced in python3.2.

Todo

Possibly change API so funcs return a value on success.

Parameters

min_py_version (int or float or tuple) – Value that represents the lowest version of python that can be used.

pyutil.sys_checks.py_gt_raise(min_py_version)[source]

Raise an error if python interpreter is not above a certain version.

pyutil.sys_checks.py_lt_exit(max_py_version)[source]

Check a user’s python version is lower than some ceiling value.

If you’ll crash on python3.4 but work on 3.3, call this func with 3.3.

Parameters

max_py_version (int or float or tuple) – The highest version of python that can be used