Auxly

This is the main documentation for Auxly, a Python library for various helper classes/functions originally intended to make shell-like scripting easier.

For more information:

Introduction

This project provides a Python 2.7/3.x library for common tasks especially when writing shell-like scripts. Some of the functionality overlaps with the standard library but the API is slightly modified.

The goal of this project is to leverage the straightforward, clean syntax of Python while avoiding some of the boilerplate code that might be necessary when using the standard library. Functions that overlap with the standard library are designed to do what you would reasonably expect (POLA) and, when necessary, fail without throwing exceptions.

Please note when using this library that operations will fail silently. This is a deliberate design decision. However, there is often a way to check if an operation has failed and optionally throw and exception if that is desirable:

auxly.filesys.copy("foo.txt", "bar") or auxly.throw()  # Throws/raises exception on failure.

Auxly provides the following modules:

The following are basic examples of Auxly (all examples can be found here):

Refer to the unit tests here for additional examples.

Status

Currently, this project is in the development release stage. While this project is suitable for use, please note that there may be incompatibilities in new releases.

Release notes are maintained in the project changelog.

Requirements

Auxly should run on any Python 2.7/3.x interpreter without additional dependencies.

Installation

Auxly can be installed with pip using the following command: pip install auxly

Additionally, Auxly can be installed from source by running: python setup.py install

API Documentation

auxly

auxly.filesys

The auxly.filesys module provides various convenience functions for working with the file system.

Library of functions related to file system contents and manipulation.

class auxly.filesys.Cwd(path='.', root=None)

Bases: object

Class to handle changing current working directory. Can be used as a context manager.

Examples:

with auxly.filesys.Cwd(auxly.filesys.homedir()):  # Temporarily set CWD.
    pass  # Do stuff here...

with auxly.filesys.Cwd("..") as cwd:  # Temporarily set CWD.
    cwd.path      # The current working directory.
    cwd.original  # The original working directory.
original = None

The original working directory path.

path = None

The new/current working directory path.

class auxly.filesys.Dir(path, *extrapath, **kwargs)

Bases: auxly.filesys.Path

Object representing a file system directory.

created()

Returns the object created date/time.

decode([encoding[, errors]]) → object

Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a UnicodeDecodeError. Other possible values are ‘ignore’ and ‘replace’ as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors.

delete()

Deletes the file. Returns true if successful, otherwise false.

exists()

Returns true if object exists, otherwise false.

isdir()

Returns true if path is for an existing directory, otherwise false.

isempty()

Returns true if object is empty, otherwise false.

isfile()

Returns true if path is for an existing file, otherwise false.

make()

Creates the directory if it does not already exist. No effect if the directory already exists.

modified()

Returns the object modified date/time.

name

Returns the base name of the path.

parent

Returns a Dir for the parent directory of this object.

path

Returns the path as a string.

size()

Returns the size of the object in bytes.

auxly.filesys.ENCODING = 'utf-8'

Default file encoding.

class auxly.filesys.File(path, *extrapath, **kwargs)

Bases: auxly.filesys.Path

Object representing a file system file. The ENCODING variable defines the default encoding.

append(content, binary=False, encoding=None)

Appends the given content to the file. Existing content is preserved. Returns true if successful, otherwise false.

appendline(content, binary=False, encoding=None)

Same as append() but adds a line break after the content.

checksum(**kwargs)

Returns the checksum of the file.

created()

Returns the object created date/time.

decode([encoding[, errors]]) → object

Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a UnicodeDecodeError. Other possible values are ‘ignore’ and ‘replace’ as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors.

delete()

Deletes the file. Returns true if successful, otherwise false.

empty()

Erases/empties the content in a file but does not delete it.

exists()

Returns true if object exists, otherwise false.

ext

Returns the file extension including the period (e.g. .txt).

isdir()

Returns true if path is for an existing directory, otherwise false.

isempty()

Returns true if object is empty, otherwise false.

isfile()

Returns true if path is for an existing file, otherwise false.

make()

Creates an empty file If the file does not already exist. No effect if the file already exist.

modified()

Returns the object modified date/time.

name

Returns the base name of the path.

parent

Returns a Dir for the parent directory of this object.

path

Returns the path as a string.

read(encoding=None)

Reads from the file and returns result as a string.

readlines(encoding=None)

Reads from the file and returns result as a list of lines with endings included.

size()

Returns the size of the object in bytes.

stem

Returns the file stem, i.e. the file name without the extension.

write(content, binary=False, encoding=None)

Writes the given content to the file. Existing content is deleted. Returns true if successful, otherwise false.

writeline(content, binary=False, encoding=None)

Same as write() but adds a line break after the content.

class auxly.filesys.Path(*path)

Bases: str

Object representing a file system path.

created()

Returns the object created date/time.

decode([encoding[, errors]]) → object

Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is ‘strict’ meaning that encoding errors raise a UnicodeDecodeError. Other possible values are ‘ignore’ and ‘replace’ as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors.

delete()

Deletes the file. Returns true if successful, otherwise false.

exists()

Returns true if object exists, otherwise false.

isdir()

Returns true if path is for an existing directory, otherwise false.

isempty()

Returns true if object is empty, otherwise false.

isfile()

Returns true if path is for an existing file, otherwise false.

modified()

Returns the object modified date/time.

name

Returns the base name of the path.

parent

Returns a Dir for the parent directory of this object.

path

Returns the path as a string.

size()

Returns the size of the object in bytes.

auxly.filesys.abspath(relpath, root=None)

Returns an absolute path based on the given root and relative path.

auxly.filesys.checksum(fpath, hasher=None, asbytes=False)

Returns the checksum of the file at the given path as a hex string (default) or as a bytes literal. Uses MD5 by default.

Attribution: Based on code from Stack Overflow.

auxly.filesys.copy(srcpath, dstpath, overwrite=True)

Copies the file or directory at srcpath to dstpath. Returns true if successful, otherwise false.

auxly.filesys.countall(path, recurse=False)

Returns the number of directories and files under the given directory path.

auxly.filesys.countdirs(path, recurse=False)

Returns the number of directories under the given directory path.

auxly.filesys.countfiles(path, recurse=False)

Returns the number of files under the given directory path.

auxly.filesys.cwd(path=None, root=None)

Returns the CWD and optionally sets it to the given path. Examples:

print(auxly.filesys.cwd())  # Get the CWD.
auxly.filesys.cwd("foo")  # Set the CWD to `foo`.
auxly.filesys.delete(path, regex=None, recurse=False, test=False)

Deletes the file or directory at path. If path is a directory and regex is provided, matching files will be deleted; recurse controls whether subdirectories are recursed. A list of deleted items is returned. If test is true, nothing will be deleted and a list of items that would have been deleted is returned.

auxly.filesys.getsize(path, recurse=False)

Returns the size of the file or directory in bytes.

auxly.filesys.homedir()

Returns the path to the current user’s home directory.

auxly.filesys.isempty(path)

Returns true if the given file or directory path is empty.

Examples:

auxly.filesys.isempty("foo.txt")  # Works on files...
auxly.filesys.isempty("bar")  # ...or directories!
auxly.filesys.makedirs(path, ignore_extsep=False)

Makes all directories required for given path; returns true if successful otherwise false. Returns true if directories already exist.

Examples:

auxly.filesys.makedirs("bar/baz")
auxly.filesys.move(srcpath, dstpath, overwrite=True)

Moves the file or directory at srcpath to dstpath. Returns true if successful, otherwise false.

auxly.filesys.rootdir()

Returns the system root directory.

auxly.filesys.walkall(startdir, regex=None, regex_entire=True, recurse=False)

Yields a File or Dir for all found files and directories within the given start directory. Can optionally filter paths using a regex pattern, either on the entire path if regex_entire is true otherwise on the file name only.

auxly.filesys.walkdirs(startdir, regex=None, regex_entire=True, recurse=False)

Yields Path object for directories found within the given start directory. Can optionally filter paths using a regex pattern, either on the entire path if regex_entire is true otherwise on the directory name only.

auxly.filesys.walkfiles(startdir, regex=None, regex_entire=True, recurse=False)

Yields a File for files found within the given start directory. Can optionally filter paths using a regex pattern, either on the entire path if regex_entire is true otherwise on the file name only.

auxly.shell

The auxly.shell module provides various convenience functions for working with the system shell.

auxly.shell.NULL = <open file '/dev/null', mode 'w'>

Null device.

class auxly.shell.Process(cmd, logpath=None)

Runs the given command in a separate shell process.

exitcode()

Returns None if the process is still running, otherwise the exit code.

isrunning()

Returns true if the process is still running, otherwise false.

pid = None

The process PID.

stop(force=False)

Stops the started process. The force flag can be useful to stop some running subprocess, e.g. notepad on Windows or something similar that might run outside the shell.

wait()

Waits for the process to complete then returns the exit code.

auxly.shell.call(cmd, **kwargs)

Calls the given shell command. Output will be displayed. Returns the exit code.

Examples:

auxly.shell.call("ls")
auxly.shell.has(cmd)

Returns true if the give shell command is available.

Examples:

auxly.shell.has("ls")  # True
auxly.shell.itererr(cmd, **kwargs)

Iterates through lines of stderr.

auxly.shell.iterout(cmd, **kwargs)

Iterates through lines of stdout.

Examples:

for line in auxly.shell.iterout("cat myfile.txt"):
    print(line)
auxly.shell.iterstd(cmd, std='out', **kwargs)

Iterates through the lines of a stderr/stdout stream for the given shell command.

auxly.shell.listerr(cmd, **kwargs)

Same as itererr() but returns a list.

auxly.shell.listout(cmd, **kwargs)

Same as iterout() but returns a list.

auxly.shell.silent(cmd, **kwargs)

Calls the given shell command. Output will not be displayed. Returns the exit code.

Examples:

auxly.shell.silent("ls")
auxly.shell.start(cmd, logpath=None, **kwargs)

Starts the given command as a separate shell process. Redirects stdin/stderr to an optional log file path. Returns a Process object.

Examples:

p = auxly.shell.start("python -m http.server")
...
p.stop()
auxly.shell.strerr(cmd, **kwargs)

Same as itererr() but returns a string.

auxly.shell.strout(cmd, **kwargs)

Same as iterout() but returns a string.

auxly.stringy

The auxly.stringy module provides various convenience functions for working with strings.

auxly.stringy.between(orig, start, end)

Returns the substring of the given string that occurs between the start and end strings.

auxly.stringy.haspattern(pattern, search)

Returns true if the given text contains the given regex pattern.

auxly.stringy.randomize(length=6, choices=None)

Returns a random string of the given length.

auxly.stringy.remove(orig, subs)

Removes the given substrings from the given string, returns the modified string.

auxly.stringy.subat(orig, index, replace)

Substitutes the replacement string/character at the given index in the given string, returns the modified string.

Examples:

auxly.stringy.subat("bit", 2, "n")
auxly.stringy.subtract(orig, tosub)

Returns the original string with the given substring removed if it is found at the end, otherwise returns just the original string.

auxly.listy

The auxly.listy module provides various convenience functions for working with lists.

auxly.listy.chunk(items, size)

Yields a generator which groups the given list items into successive chunks of the given size.

Attribution: Written by Ned Batchelder and originally posted on Stack Overflow.

Examples:

list(auxly.listy.chunk([1,2,3,4,5,6,7,8], 3))
# [[1, 2, 3], [4, 5, 6], [7, 8]]
auxly.listy.index(items, num)

Returns the item at the given index, otherwise AuxlyError.

auxly.listy.isiterable(item)

Returns true if the given item is iterable.

auxly.listy.iterate(items)

Iterates over the given items, whether they are iterable or not. Strings are not iterated per character.

auxly.listy.smooth(items)

Yields a generator which smooths all items as if the given list was of depth 1.

Examples:

list(auxly.listy.smooth([1,[2,[3,[4]]]]))
# [1, 2, 3, 4]