API Documentation¶
tea api documentation¶
tea.console
Module¶
-
tea.console.
clear_screen
(numlines=100)[source]¶ Clear the console.
Parameters: numlines (int) – This is an optional argument used only as a fall-back if the operating system console doesn’t have clear screen function. Return type: None
-
tea.console.
getch
()[source]¶ Cross-platform getch() function.
Same as the getch function from msvcrt library, but works on all platforms. :rtype: str :return: One character got from standard input.
-
tea.console.color.
set_color
(fg='normal', bg='normal', fg_dark=False, bg_dark=False, underlined=False)[source]¶ Set the console color.
>>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal
-
tea.console.color.
strip_colors
(text)[source]¶ Helper function used to strip out the color tags so other function can determine the real text line lengths.
Parameters: text (str) – Text to strip color tags from Return type: str
Returns: Stripped text.
-
tea.console.color.
cprint
(text, fg='normal', bg='normal', fg_dark=False, bg_dark=False, underlined=False, parse=False)[source]¶ Prints string in to stdout using colored font.
See L{set_color} for more details about colors.
Parameters:
-
tea.console.color.
colorize_output
(output, colors, indent=0)[source]¶ Prints output to console using provided color mappings.
Color mapping is dict with regular expressions as key and tuple of two as values. Key is used to match if line should be colorized and tuple contains color to be used and boolean value that indicates if dark foreground is used. For example:
>>> CLS = { >>> re.compile(r'^(--- .*)$'): (Color.red, False) >>> }
will colorize lines that start with ‘—’ to red.
If different parts of line needs to be in different color then dict must be supplied in colors with keys that are named group from regular expression and values that are tuples of color and boolean that indicates if dark foreground is used. For example:
>>> CLS = { >>> re.compile(r'^(?P<key>user:\s+)(?P<user>.*)$'): { >>> 'key': (Color.yellow, True), >>> 'user': (Color.cyan, False) >>> } >>> }
will colorize line ‘user: Some user’ so that ‘user:’ part is yellow with dark foreground and ‘Some user’ part is cyan without dark foreground.
-
tea.console.format.
format_page
(text)[source]¶ Formats the text for output adding ASCII frame around the text.
Parameters: text (str) – Text that needs to be formatted. Return type: string Returns: Formatted string.
-
tea.console.format.
table
(text)[source]¶ Formats the text as a table
Text in format:
first | second row 2 col 1 | 4
Will be formatted as:
+-------------+--------+ | first | second | +-------------+--------+ | row 2 col 1 | 4 | +-------------+--------+
Parameters: text (str) – Text that needs to be formatted. Return type: str Returns: Formatted string.
-
tea.console.format.
hbar
(width)[source]¶ Returns ASCII HBar
+---+
with the specified width.Parameters: width (int) – Width of the central part of the bar. Return type: str Returns: ASCII HBar.
-
tea.console.format.
print_page
(text)[source]¶ Formats the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text. Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text. My [BG_BLUE]blue background[NORMAL] text.
-
tea.console.format.
wrap_text
(text, width=80)[source]¶ Wraps text lines to maximum width characters.
Wrapped text is aligned against the left text border.
Parameters: Return type: Returns: Wrapped text.
-
tea.console.format.
rjust_text
(text, width=80, indent=0, subsequent=None)[source]¶ Same as L{wrap_text} with the difference that the text is aligned against the right text border.
Parameters:
-
tea.console.format.
center_text
(text, width=80)[source]¶ Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the line width will not be checked.
Parameters: Return type: Returns: Centered text.
tea.decorators
Module¶
-
tea.decorators.
docstring
(documentation, prepend=False, join='')[source]¶ - Decorator that will prepend or append a string to the current
documentation of the target function.
This decorator should be robust even if
func.__doc__
is None (for example, if -OO was passed to the interpreter).Usage:
@docstring('Appended this line') def func(): "This docstring will have a line below." pass >>> print(func.__doc__) This docstring will have a line below. Appended this line
param str documentation: Documentation string that should be added, appended or prepended to the current documentation string. param bool prepend: Prepend the documentation string to the current documentation if True else append. default=False param str join: String used to separate docstrings. default=’
‘
-
tea.decorators.
combomethod
(method=None, static=False)[source]¶ Creates a class method or static method that will be used when you call it on the class but can be overridden by an instance method of the same name that will be called when the method is called on the instance.
Usage:
class Foo(object): class_variable = 2 def __init__(self): self.instance_variable = 3 # Override class variable for test case self.class_variable = 4 @combomethod(static=True) def static_and_instance(x): return x + 1 @static_and_instance.instance def static_and_instance(self, x): return x + self.instance_variable @combomethod def class_and_instance(cls, x): return x + cls.class_variable @class_and_instance.instance def class_and_instance(self, x): return x + self.instance_variable >>> Foo.static_and_instance(100) 101 >>> Foo.class_and_instance(100) 102 >>> f = Foo() >>> f.static_and_instance(100) 103 >>> f.class_and_instance(100) 103
tea.dsa
Module¶
Data structures and algorithms module
-
class
tea.dsa.config.
Config
(filename=None, data=None, fmt=None, encoding=u'utf-8', auto_save=True)[source]¶ Configuration class
tea.logger
Module¶
Logging module¶
This logging module is designed as a wrapper around the python logging module.
When the module is loaded it configure the logging object with some default parameters (log to stderr with DEBUG level). After that, user can call the L{configure_logger} function and configure logging to file and stderr.
Usage¶
>>> import logging
>>> import tempfile
>>> from tea.logger import configure_logging
>>> configure_logging(filename=tempfile.mktemp())
>>> logger = logging.getLogger('test')
>>> logger.debug('Debug level log entry')
>>> logger.info('Info level log entry')
>>> logger.warning('Warn level log entry')
WARNING - Warn level log entry [test:1]
>>> logger.error('Error level log entry')
ERROR - Error level log entry [test:1]
>>> logger.critical('Critical level log entry')
CRITICAL - Critical level log entry [test:1]
>>> try:
... raise Exception('Test exception')
... except:
... logger.exception('Error level log entry with stack trace')
ERROR - Error level log entry with stack trace [test:4]
Traceback (most recent call last):
...
Exception: Test exception
-
tea.logger.
configure_logging
(filename=None, filemode='a', datefmt='%Y.%m.%d %H:%M:%S', fmt='%(asctime)s.%(msecs)03d %(levelname)11s: %(message)s [%(name)s:%(lineno)d]', stdout_fmt='%(levelname)-11s - %(message)s [%(name)s:%(lineno)d]', level=10, stdout_level=30, initial_file_message='', max_size=1048576, rotations_number=5, remove_handlers=True)[source]¶ Configure logging module.
Parameters: - filename (str) – Specifies a filename to log to.
- filemode (str) – Specifies the mode to open the log file. Values:
'a'
,'w'
. Default:a
- datefmt (str) – Use the specified date/time format.
- fmt (str) – Format string for the file handler.
- stdout_fmt (str) – Format string for the stdout handler.
- level (int) – Log level for the file handler. Log levels are the same
as the log levels from the standard
logging
module. Default:logging.DEBUG
- stdout_level (int) – Log level for the stdout handler. Log levels are
the same as the log levels from the standard
logging
module. Default:logging.WARNING
- initial_file_message (str) – First log entry written in file.
- max_size (int) – Maximal size of the logfile. If the size of the file exceed the maximal size it will be rotated.
- rotations_number (int) – Number of rotations to save
- remove_handlers (bool) – Remove all existing handlers
Return type:
-
tea.logger.log.
configure_logging
(filename=None, filemode='a', datefmt='%Y.%m.%d %H:%M:%S', fmt='%(asctime)s.%(msecs)03d %(levelname)11s: %(message)s [%(name)s:%(lineno)d]', stdout_fmt='%(levelname)-11s - %(message)s [%(name)s:%(lineno)d]', level=10, stdout_level=30, initial_file_message='', max_size=1048576, rotations_number=5, remove_handlers=True)[source]¶ Configure logging module.
Parameters: - filename (str) – Specifies a filename to log to.
- filemode (str) – Specifies the mode to open the log file. Values:
'a'
,'w'
. Default:a
- datefmt (str) – Use the specified date/time format.
- fmt (str) – Format string for the file handler.
- stdout_fmt (str) – Format string for the stdout handler.
- level (int) – Log level for the file handler. Log levels are the same
as the log levels from the standard
logging
module. Default:logging.DEBUG
- stdout_level (int) – Log level for the stdout handler. Log levels are
the same as the log levels from the standard
logging
module. Default:logging.WARNING
- initial_file_message (str) – First log entry written in file.
- max_size (int) – Maximal size of the logfile. If the size of the file exceed the maximal size it will be rotated.
- rotations_number (int) – Number of rotations to save
- remove_handlers (bool) – Remove all existing handlers
Return type:
tea.msg
Module¶
-
tea.msg.
send_mail
(subject, sender, to, message, html_message=None, cc=None, bcc=None, attachments=None, host=None, port=None, auth_user=None, auth_password=None, use_tls=False, fail_silently=False)[source]¶ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the ‘To’ field.
Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly.
-
tea.msg.
send_mass_mail
(datatuple, fail_silently=False, auth_user=None, auth_password=None)[source]¶ Given a datatuple of (subject, message, sender, recipient_list), sends each message to each recipient list. Returns the number of e-mails sent.
If auth_user and auth_password are set, they’re used to log in.
Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly.
Simple and complete library for sending emails
-
class
tea.msg.mail.
SMTPConnection
(host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False)[source]¶ A wrapper that manages the SMTP network connection.
-
class
tea.msg.mail.
EmailMessage
(subject='', body='', sender=None, to=None, cc=None, bcc=None, attachments=None, headers=None, connection=None)[source]¶ A container for email information.
Initialize a single email message (which can be sent to multiple recipients).
All strings used to create the message can be unicode strings (or UTF-8 bytestrings). The SafeMIMEText class will handle any necessary encoding conversions.
-
recipients
()[source]¶ Returns a list of all recipients of the email (includes direct addressees as well as Bcc entries).
-
attach
(filename=None, content=None, mimetype=None)[source]¶ Attaches a file with the given filename and content. The filename can be omitted (useful for multipart/alternative messages) and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass it is inserted directly into the resulting message attachments.
-
-
class
tea.msg.mail.
EmailMultiAlternatives
(subject='', body='', sender=None, to=None, cc=None, bcc=None, attachments=None, headers=None, connection=None)[source]¶ A version of EmailMessage that makes it easy to send multipart/alternative messages. For example, including text and HTML versions of the text is made easier.
Initialize a single email message (which can be sent to multiple recipients).
All strings used to create the message can be unicode strings (or UTF-8 bytestrings). The SafeMIMEText class will handle any necessary encoding conversions.
-
tea.msg.mail.
send_mail
(subject, sender, to, message, html_message=None, cc=None, bcc=None, attachments=None, host=None, port=None, auth_user=None, auth_password=None, use_tls=False, fail_silently=False)[source]¶ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the ‘To’ field.
Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly.
-
tea.msg.mail.
send_mass_mail
(datatuple, fail_silently=False, auth_user=None, auth_password=None)[source]¶ Given a datatuple of (subject, message, sender, recipient_list), sends each message to each recipient list. Returns the number of e-mails sent.
If auth_user and auth_password are set, they’re used to log in.
Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly.
tea.process
Module¶
-
tea.process.
execute
(command, *args, **kwargs)[source]¶ Execute a command with arguments and wait for output. Arguments should not be quoted!
Keyword arguments:
Parameters: Example:
>>> code = 'import sys;sys.stdout.write('out');sys.exit(0)' >>> status, out, err = execute('python', '-c', code) >>> print('status: %s, output: %s, error: %s' % (status, out, err)) status: 0, output: out, error: >>> code = 'import sys;sys.stderr.write('out');sys.exit(1)' >>> status, out, err = execute('python', '-c', code) >>> print('status: %s, output: %s, error: %s' % (status, out, err)) status: 1, output: , error: err
-
tea.process.
execute_and_report
(command, *args, **kwargs)[source]¶ Executes a command with arguments and wait for output. If execution was successful function will return True, if not, it will log the output using standard logging and return False.
-
tea.process.
get_processes
(sort_by_name=True)[source]¶ Retrieves a list of processes sorted by name.
Parameters: sort_by_name (bool) – Sort the list by name or by process ID’s Return type: list[(int, str)] or list[(int, str, str)] Returns: List of process id, process name and optional cmdline tuples
-
tea.process.
find
(name, arg=None)[source]¶ Find process by name or by argument in command line if arg param is available.
Parameters: Return type: tea.process.base.IProcess
Returns: Process if found
-
tea.process.
kill
(pid)[source]¶ Kills a process by it’s process ID.
Parameters: pid (int) – Process ID of the process to kill.
-
class
tea.process.base.
Process
(command, arguments=None, env=None, stdout=None, stderr=None, redirect_output=True, working_dir=None)[source]¶ Abstract base class for the Process class that is implemented for every platform in it’s own module.
Simple example of Process class usage can be:
>>> from tea.process import Process >>> p = Process('python', ['-c', 'import time;time.sleep(5);print(3)']) >>> p.start() >>> p.is_running True >>> p.wait() True >>> p.read() b'3\n' >>> p.eread() b''
Creates the Process object providing the command and it’s command line arguments.
The only required parameter is the command to execute. It’s important to note that the constructor only initializes the class, it doesn’t executes the process. To actually execute the process you have to call :met:`start`.
Parameters: - command (str) – Path to the executable file.
- arguments (list) – list of command line arguments passed to the command
- env (dict) – Optional additional environment variables that will be added to the subprocess environment or that override currently set environment variables.
- stdout (str) – Path to the file to which standard output would be redirected.
- stderr (str) – Path to the file to which standard error would be redirected.
- redirect_output (bool) – True if you want to be able to get the standard output and the standard error of the subprocess, otherwise it will be redirected to /dev/null. If stdout or stderr are provided redirect_output will automatically be set to True.
- working_dir (str) – Set the working directory from which the process will be started.
-
classmethod
immutable
(pid, command)[source]¶ Create an immutable process object used for listing processes on the system
-
command
¶ Command
-
arguments
¶ Arguments
-
wait
(timeout=None)[source]¶ Waits for the process to finish.
It will wait for the process to finish running. If the timeout is provided, the function will wait only
timeout
amount of seconds and then return to it’s caller.Parameters: timeout (None or int) – None if you want to wait to wait until the process actually finishes, otherwise it will wait just the timeout
number of seconds.Return type: bool Returns: Return value only makes sense if you provided the timeout parameter. It will indicate if the process actually finished in the amount of time specified, i.e. if the we specify 3 seconds and the process actually stopped after 3 seconds it will return True
otherwise it will returnFalse
.
-
is_running
¶ Property that indicates if the process is still running.
Return type: bool Returns: True if the process is still running False otherwise
-
pid
¶ Property that returns the PID of the process if it is running.
Return type: int Returns: process id of the running process
-
exit_code
¶ Property that returns the exit code if the process has finished running.
Return type: int or None Returns: Exit code or None if the process is still running
-
write
(string)[source]¶ Write a string to the process standard input.
Parameters: string (str) – String to write to the process standard input
tea.shell
Module¶
This module mimics some of the behaviors of the builtin shutil
module, adding logging to all operations and abstracting some other useful
shell commands (functions).
-
tea.shell.
search
(path, matcher='*', dirs=False, files=True)[source]¶ Recursive search function.
Parameters: - path – path to search recursively
- matcher – string pattern to search for or function that returns True/False for a file argument
- dirs – if True returns directories that match the pattern
- files – if True returns files that match the patter
-
tea.shell.
goto
(*args, **kwds)[source]¶ Context object for changing directory.
Usage:
>>> with goto(directory) as ok: ... if not ok: ... print 'Error' ... else: ... print 'All OK'
-
tea.shell.
mkdir
(path[, mode=0755])[source]¶ Create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive.
Parameters: Return type: Returns: True if succeeded else False
-
tea.shell.
gcopy
(pattern, destination)[source]¶ Copy all file found by glob.glob(pattern) to destination directory
-
tea.shell.
move
(source, destination)[source]¶ Recursively move a file or directory to another location.
If the destination is on our current file system, then simply use rename. Otherwise, copy source to the destination and then remove source.
Parameters: Return type: Returns: True if the operation is successful, False otherwise.
-
tea.shell.
gmove
(pattern, destination)[source]¶ Move all file found by glob.glob(pattern) to destination directory
-
tea.shell.
remove
(path)[source]¶ Delete a file or directory
Parameters: path (str) – Path to the file or directory that needs to be deleted. Return type: bool
Returns: True if the operation is successful, False otherwise.
-
tea.shell.
gremove
(pattern)[source]¶ Remove all file found by glob.glob(pattern)
Parameters: pattern (str) – Pattern of files to remove
tea.system
Module¶
-
tea.system.
get_username
()¶ Get the username from the environment or password database.
First try various environment variables, then the password database. This works on Windows as long as USERNAME is set.
tea.utils
Module¶
-
tea.utils.
get_object
(path='', obj=None)[source]¶ Returns an object from a dot path.
Path can either be a full path, in which case the get_object function will try to import the modules in the path and follow it to the final object. Or it can be a path relative to the object passed in as the second argument.
Parameters: Returns: - Object at the end of the path, or list of non hidden objects
if we use the star query.
Return type: Example for full paths:
>>> get_object('os.path.join') <function join at 0x1002d9ed8> >>> get_object('tea.process') <module 'tea.process' from 'tea/process/__init__.pyc'>
Example for relative paths when an object is passed in:
>>> import os >>> get_object('path.join', os) <function join at 0x1002d9ed8>
Example for a star query. (Star query can be used only as the last element of the path:
>>> get_object('tea.dsa.*') [] >>> get_object('tea.dsa.singleton.*') [<class 'tea.dsa.singleton.Singleton'>, <class 'tea.dsa.singleton.SingletonMetaclass'> <module 'six' from '...'>] >>> get_object('tea.dsa.*') [<module 'tea.dsa.singleton' from '...'>] # Since we imported it
-
class
tea.utils.
Loader
[source]¶ Module loader class loads recursively a module and all it’s submodules.
Loaded modules will be stored in the
modules
attribute of the loader as a dictionary of {module_path: module} key, value pairs.Errors accounted during the loading process will not stop the loading process. They will be stored in the
errors
attribute of the loader as a dictionary of {module_path: exception} key, value pairs.Usage:
loader = Loader() loader.load('foo') loader.load('baz.bar', 'boo') import baz loader.load(baz)
-
tea.utils.
load_subclasses
(klass, modules=None)[source]¶ Load recursively all submodules of the modules and return all the subclasses of the provided class
Parameters: - klass (str or list of str) – Class whose subclasses we want to load.
- modules – List of additional modules or module names that should be recursively imported in order to find all the subclasses of the desired class. Default: None
- FIXME: This function is kept only for backward compatibility reasons, it
- should not be used. Deprecation warning should be raised and it should
be replaces by the
Loader
class.
-
tea.utils.compress.
unzip
(archive, destination, filenames=None)[source]¶ Unzip the a complete zip archive into destination directory, or unzip a specific file(s) from the archive.
- Usage:
>>> output = os.path.join(os.getcwd(), 'output') >>> # Archive can be an instance of a ZipFile class >>> archive = zipfile.ZipFile('test.zip', 'r') >>> # Or just a filename >>> archive = 'test.zip' >>> # Extracts all files >>> unzip(archive, output) >>> # Extract only one file >>> unzip(archive, output, 'my_file.txt') >>> # Extract a list of files >>> unzip(archive, output, ['my_file1.txt', 'my_file2.txt']) >>> unzip_file('test.zip', 'my_file.txt', output)
Parameters:
-
tea.utils.compress.
mkzip
(archive, items, mode='w', save_full_paths=False)[source]¶ Recursively zip a directory
Parameters:
-
class
tea.utils.daemon.
Daemon
(pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null')[source]¶ A generic daemon class.
Usage: subclass the Daemon class and override the run() method
-
daemonize
()[source]¶ Do the UNIX double-fork magic
See Stevens’ “Advanced Programming in the UNIX Environment” for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
-