PyLib API Reference¶
Version: 1.0.0
author: | Ken Lowrie |
---|
pylib
— aka kenl380.pylib¶
Library of common APIs for Python Applications.
PyLib is a set of common APIs and Classes that are used by many of my personal Python applications and packages. In this initial version of the library, I’ve stripped it down to just those things that I have functional unittests for. As I have time to add additional tests and documentation, I will add more functionality back in.
I recommend importing this package using the syntax:
import kenl380.pylib as pylib
So that you only need to use the pylib
part of the namespace, e.g.:
pylib.USER
pylib.context(__file__)
pylib Module-wide data¶
Yes, module-wide data is another way of saying Global (ugh) variables. In the current version, there are three (3) of them.
-
pylib.
USER
- `str` object¶ This is the name of the currently logged-in user.
-
pylib.
COMPUTER
- `str` object¶ This is the host name where your app is running.
-
pylib.
TEMPDIR
- `str` object¶ This points to a writable location for temporary files
pylib.context Class¶
The context class provides a quick way to get at some useful information about the current module.
-
class
pylib.
context
(module, alias=None)[source]¶ Provides context to a Python module.
The context object provides methods to give useful context to a Python module. Things like current location, fully qualified script name, an alias and more.
when you instantiate one of these, you pass in __file__ if defined, otherwise sys.argv[0].
Parameters: - module (str) – the fully qualified path for this module
- alias (str, optional) – the preferred alias for this module, defaults to basename
of the
module
variable.
Examples
For example, add the following code to your main module.
import kenl380.pylib as pylib def context(): try: myself = __file__ except NameError: myself = argv[0] return pylib.context(myself) me = context()
Now, the
me
object can be used to extract useful information about the module, such as:me.whereami()
to get the fully qualified pathname of your script.-
alias
()[source]¶ Returns the alias (shortname) of the current module
By default, the alias is simply the basename (module name without extension) of the module; however, you can override that by passing in a specific value for the alias when you construct the object.
Returns: The alias for the current module Return type: str
-
pyVersionStr
()[source]¶ Version of Python running my script
Returns: A descriptive string containing the version of Python running this script. Return type: str
pylib.ntpx Class¶
The pylib.ntpx class will probably be deprecated soon. Python 3’s pathlib
is more flexible and has much more support. At the very least, I should refactor
ntpx to use pathlib
if running on 3.x.
-
class
pylib.
ntpx
(path, normalize=True)[source]¶ Implements Windows NT command shell path manipulation.
This class implements methods for manipulating paths, including a simple formatter that accepts a format string similar to what the Windows NT command shell allows.
Parameters: - path (str) – A path that you want to manipulate
- normalize (bool) – Whether or not to normalize the path that is passed in. Default is True.
Examples
print ntpx('c:/dir/foo.ext').format('dp') - prints 'c:/dir/' print ntpx('c:/dir/foo.ext').format('nx') - prints 'foo.ext'
Of course on any Posix system, drive letter doesn’t make sense, so if you run this same code on Mac OS X or Linux, you’d get:
print ntpx('c:/dir/foo.ext').format('dp') - prints 'CWD/c:/dir/' print ntpx('c:/dir/foo.ext').format('nx') - prints 'foo.ext'
Todo
Refactor this code when running on Python 3 to use the
pathlib
module, which is a superior alternative with many more features.-
all
()[source]¶ Returns a tuple containing all elements of the object
- This method returns all elements of the path in the form of a tuple.
- e.g.: (abs_path, drive_letter, path_only, rootname, extension, filesize, time_in_seconds).
Returns: All elements of the path associated with this object as a tuple. Return type: tuple Notes
If path points to a non-existant file, the size and datetime will be returned as None (NoneType).
-
datetime
()[source]¶ returns the modified date and time of the file in seconds
Returns: Modify DateTime of the file in seconds or None if file doesn’t exist Return type: int
-
drive
()[source]¶ returns the drive letter
Returns: The drive letter for the path Return type: str Notes
Drive letters are a Windows thing. On Posix platforms, this will return an empty string.
-
format
(fmt)[source]¶ Returns string representing the items specified in the format string
The format string can contain:
d - drive letter p - path n - name x - extension z - file size t - file time in seconds
And, you can string them together, e.g. dpnx returns the fully qualified name.
On platforms like Unix, where drive letter doesn’t make sense, it’s simply ignored when used in a format string, making it easy to construct fully qualified path names in an os independent manner.
Parameters: fmt (str) – A string representing the elements you want returned. Returns: A string containing the elements of the path requested in fmt Return type: str
pylib methods¶
-
pylib.
parent
(pathspec)[source]¶ Return the parent directory of
pathspec
.This function calls abspath() on pathspec before splitting the path. If you pass in a partial path, it will return the normalized absolute path, and not just any relative path that was on the original pathspec.
Parameters: pathspec (str) – The path (or partial path) whose parent you want to extract Returns: The parent directory of pathspec
Return type: str
-
pylib.
pushd
(dir=None, throw_if_dir_invalid=True)[source]¶ Push the current working directory (CWD) onto a stack, set CWD to ‘dir’
Save the CWD onto a global stack so that we can return to it later. If dir is None, the function simply stores the CWD onto the stack and returns. Use
popd()
to restore the original directory.Parameters: - dir (str, optional) – The directory to switch to or None. If None, the default if it is not passed, this function will simply push the current working directory onto the global stack and return.
- throw_if_dir_invalid (bool, optional) – Whether or not to pass back up any exception raised by chdir(). Default is True.
Returns: - True (bool) – Success
- False (bool) – Failure
Raises: OSError
– If throw_if_dir_invalid is True and chdir raises an exception, this function will chain the same exception as chdir, typically OSErrorTypeError
– If the type ofdir
is not an instance of str
Notes
This method and its counterpart
popd()
are not thread safe!
-
pylib.
popd
(pop_all=False, throw_if_dir_invalid=True)[source]¶ Restore current working directory to previous directory.
The previous directory is whatever it was when last
pushd()
was last called.pushd()
creates a stack, so each call to popd() simply sets the CWD back to what it was on the prior pushd() call.Parameters: - pop_all (bool, optional) – When pop_all is True, sets the CWD to the state when pushd() was first called. Does NOT call os.getcwd() for intervening paths, only the final path.
- throw_if_dir_invalid (bool, optional) – Whether or not to pass back up any exception raised by chdir(). Default is True.
Returns: - True (bool) – Success
- False (bool) – Failure
Raises: OSError
– If throw_if_dir_invalid is True and chdir raises an exception, this function will chain the same exception as chdir, typically OSErrorValueError
– If popd() called on an empty stack; i.e. beforepushd()
has been called.
Notes
This method and its counterpart
pushd()
are not thread safe!