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

exception auxly.AuxlyError

Default Auxly error.

auxly.callstop(*args, **kwargs)

Limits the number of times a function can be called. Can be used as a function decorator or as a function that accepts another function. If used as a function, it returns a new function that will be call limited.

Params:
  • func (func) - Function to call. Only available when used as a function.

Examples:

call = callstop(myfunc, limit=3)
call(myarg1, myarg2)
auxly.isadmin()

Returns true if the script is being run in admin mode, otherwise false.

auxly.islinux()

Returns true if host OS is Linux.

auxly.ismac()

Returns true if host OS is Mac.

auxly.iswindows()

Returns true if host OS is Windows.

auxly.open(target)

Opens the target file or URL in the default application.

Attribution: Written by user4815162342 and originally posted on Stack Overflow.

Examples:

auxly.open("myfile.txt")
auxly.open("https://www.github.com/")
auxly.throw(*args, **kwargs)

Convenience function for throwing/raising exceptions. Usefully with compound “or” statements and similar situations. Throws an AuxlyError by default unless another exception is provided as the first argument.

Examples:

throw()
throw("error message")
throw(ValueError)
throw(ValueError, "error message")
auxly.trycatch(*args, **kwargs)

Wraps a function in a try/catch block. Can be used as a function decorator or as a function that accepts another function.

Params:
  • func (func) - Function to call. Only available when used as a function.
  • oncatch (str) [kwargs] - Function to call if an exception is caught.
  • rethrow (str) [kwargs] - If true, exception will be re-thrown.

Examples:

trycatch(myfunc)(myarg1, myarg2, kwarg=mykwarg)
trycatch(myfunc, oncatch=mycatchfunc)(myarg1, myarg2, kwarg=mykwarg)
trycatch(myfunc, rethrow=True)(myarg1, myarg2, kwarg=mykwarg)
auxly.verbose(enabled)

Returns normal print function if enabled, otherwise a dummy print function is returned which will suppress output.

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.

auxly.filesys.ENCODING = 'utf-8'

Default file encoding.

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

Bases: auxly.filesys._FileSysObject

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.

delete()

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

dirpath()

Returns a Path object for the directory associated with this object.

empty()

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

exists()

Returns true if object exists, otherwise false.

isdir()

Returns true if object is directory, otherwise false.

isempty()

Returns true if object is empty, otherwise false.

isfile()

Returns true if object is file, otherwise false.

modified()

Returns the object modified date/time.

path = None

The file path as a Path object.

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.

size()

Returns the size of the object in bytes.

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: auxly.filesys._FileSysObject, 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.

dir = None

The directory path.

dirpath()

Returns a Path object for the directory associated with this object.

exists()

Returns true if object exists, otherwise false.

ext = None

The file extension, e.g. “.txt”.

file = None

The file name without extension, e.g. “myfile”.

filename = None

The file name with extension, e.g. “myfile.txt”.

isdir()

Returns true if object is directory, otherwise false.

isempty()

Returns true if object is empty, otherwise false.

isfile()

Returns true if object is file, otherwise false.

modified()

Returns the object modified date/time.

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.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.

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.walkdirs(startdir, regex=None, recurse=True, regex_entire=True)

Yields the absolute paths of 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, recurse=True, regex_entire=True)

Yields the absolute paths of 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(full, start, end)

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

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

Returns a random string of the given length.

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.listy

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

auxly.listy.chunk(l, n)

Yields a generator which groups the given list into successive n-size chunks.

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.smooth(l)

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

Examples:

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