sciris.sc_printing

Printing/notification functions.

Highlights:
  • sc.heading(): print text as a ‘large’ heading

  • sc.colorize(): print text in a certain color

  • sc.pr(): print full representation of an object, including methods and each attribute

  • sc.sigfigs(): truncate a number to a certain number of significant figures

  • sc.progressbar(): show a (text-based) progress bar

  • sc.capture(): capture text output (e.g., stdout) as a variable

Functions

blank

Tiny function to print n blank lines, 3 by default

colorize

Colorize output text.

createcollist

Creates a string for a nice columnated list (e.g.

heading

Create a colorful heading.

indent

Small wrapper to make textwrap more user friendly.

objatt

Return a sorted string of object attributes for the Python __repr__ method

objectid

Return the object ID as per the default Python __repr__ method

objmeth

Return a sorted string of object methods for the Python __repr__ method

objprop

Return a sorted string of object properties for the Python __repr__ method

objrepr

Return useful printout for the Python __repr__ method

percentcomplete

Display progress.

pr

Shortcut for printing the pretty repr for an object -- similar to prettyprint

prepr

Akin to "pretty print", returns a pretty representation of an object -- all attributes (except any that are skipped), plust methods and ID.

printarr

Print a numpy array nicely.

printblue

Alias to print(colors.blue(s))

printcyan

Alias to print(colors.cyan(s))

printdata

Nicely print a complicated data structure, a la Matlab.

printgreen

Alias to print(colors.green(s))

printmagenta

Alias to print(colors.magenta(s))

printred

Alias to print(colors.red(s))

printtologfile

Append a message string to a file specified by a filename name/path.

printv

Optionally print a message and automatically indent.

printvars

Print out a list of variables.

printyellow

Alias to print(colors.yellow(s))

progressbar

Call in a loop to create terminal progress bar.

sigfig

Return a string representation of variable x with sigfigs number of significant figures

slacknotification

Send a Slack notification when something is finished.

Classes

capture

Captures stdout (e.g., from print()) as a variable.

createcollist(items, title=None, strlen=18, ncol=3)[source]

Creates a string for a nice columnated list (e.g. to use in __repr__ method)

objectid(obj)[source]

Return the object ID as per the default Python __repr__ method

objatt(obj, strlen=18, ncol=3)[source]

Return a sorted string of object attributes for the Python __repr__ method

objmeth(obj, strlen=18, ncol=3)[source]

Return a sorted string of object methods for the Python __repr__ method

objprop(obj, strlen=18, ncol=3)[source]

Return a sorted string of object properties for the Python __repr__ method

objrepr(obj, showid=True, showmeth=True, showprop=True, showatt=True, dividerchar='—', dividerlen=60)[source]

Return useful printout for the Python __repr__ method

prepr(obj, maxlen=None, maxitems=None, skip=None, dividerchar='—', dividerlen=60, use_repr=True, maxtime=3, die=False)[source]

Akin to “pretty print”, returns a pretty representation of an object – all attributes (except any that are skipped), plust methods and ID. Usually used via the interactive sc.pr() (which prints), rather than this (which returns a string).

Parameters
  • obj (anything) – the object to be represented

  • maxlen (int) – maximum number of characters to show for each item

  • maxitems (int) – maximum number of items to show in the object

  • skip (list) – any properties to skip

  • dividerchar (str) – divider for methods, attributes, etc.

  • divierlen (int) – number of divider characters

  • use_repr (bool) – whether to use repr() or str() to parse the object

  • maxtime (float) – maximum amount of time to spend on trying to print the object

  • die (bool) – whether to raise an exception if an error is encountered

pr(obj, *args, **kwargs)[source]

Shortcut for printing the pretty repr for an object – similar to prettyprint

Example:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
print(df) # See just the data
sc.pr(df) # See all the methods too
blank(n=3)[source]

Tiny function to print n blank lines, 3 by default

indent(prefix=None, text=None, suffix='\n', n=0, pretty=False, width=70, **kwargs)[source]

Small wrapper to make textwrap more user friendly.

Parameters
  • prefix (str) – text to begin with (optional)

  • text (str) – text to wrap

  • suffix (str) – what to put on the end (by default, a newline)

  • n (int) – if prefix is not specified, the size of the indent

  • pretty (bool) – whether to use pprint to format the text

  • width (int) – maximum width before wrapping (if None, don’t wrap)

  • kwargs (dict) – passed to textwrap.fill()

Examples:

prefix = 'and then they said: '
text = 'blah '*100
print(sc.indent(prefix, text))

print('my fave is: ' + sc.indent(text=rand(100), n=12))

New in version 1.3.1: more flexibility in arguments

sigfig(x, sigfigs=5, SI=False, sep=False, keepints=False)[source]

Return a string representation of variable x with sigfigs number of significant figures

Parameters
  • x (int/float/arr) – the number(s) to round

  • sigfigs (int) – number of significant figures to round to

  • SI (bool) – whether to use SI notation

  • sep (bool/str) – if provided, use as thousands separator

  • keepints (bool) – never round ints

Examples:

x = 32433.3842
sc.sigfig(x, SI=True) # Returns 32.433k
sc.sigfig(x, sep=True) # Returns 32,433
printarr(arr, arrformat='%0.2f  ')[source]

Print a numpy array nicely.

Example:

sc.printarr(pl.rand(3,7,4))

Version: 2014dec01

printdata(data, name='Variable', depth=1, maxlen=40, indent='', level=0, showcontents=False)[source]

Nicely print a complicated data structure, a la Matlab.

Note: this function is deprecated.

Parameters
  • data – the data to display

  • name – the name of the variable (automatically read except for first one)

  • depth – how many levels of recursion to follow

  • maxlen – number of characters of data to display (if 0, don’t show data)

  • indent – where to start the indent (used internally)

Version: 2015aug21

printvars(localvars=None, varlist=None, label=None, divider=True, spaces=1, color=None)[source]

Print out a list of variables. Note that the first argument must be locals().

Parameters
  • localvars – function must be called with locals() as first argument

  • varlist – the list of variables to print out

  • label – optional label to print out, so you know where the variables came from

  • divider – whether or not to offset the printout with a spacer (i.e. ——)

  • spaces – how many spaces to use between variables

  • color – optionally label the variable names in color so they’re easier to see

Example:

>>> a = range(5)
>>> b = 'example'
>>> sc.printvars(locals(), ['a','b'], color='green')

Another useful usage case is to print out the kwargs for a function:

>>> sc.printvars(locals(), kwargs.keys())

Version: 2017oct28

colorize(color=None, string=None, doprint=None, output=False, enable=True, showhelp=False, fg=None, bg=None, style=None)[source]

Colorize output text.

Parameters
  • color (str) – the color you want (use ‘bg’ with background colors, e.g. ‘bgblue’); alternatively, use fg, bg, and style

  • string (str) – the text to be colored

  • doprint (bool) – whether to print the string (default true unless output)

  • output (bool) – whether to return the modified version of the string (default false)

  • enable (bool) – switch to allow sc.colorize() to be easily turned off without converting to a print() statement

  • showhelp (bool) – show help rather than changing colors

Examples:

sc.colorize('green', 'hi') # Simple example
sc.colorize(['yellow', 'bgblack']); print('Hello world'); print('Goodbye world'); colorize() # Colorize all output in between
bluearray = sc.colorize(color='blue', string=str(range(5)), output=True); print("c'est bleu: " + bluearray)
sc.colorize('magenta') # Now type in magenta for a while
sc.colorize() # Stop typing in magenta
sc.colorize('cat in the hat', fg='#ffa044', bg='blue', style='italic+underline') # Alternate usage example

To get available colors, type sc.colorize(showhelp=True).

New in version 1.3.1: “doprint” argument; ansicolors shortcut
heading(string=None, *args, color=None, divider=None, spaces=None, spacesafter=None, minlength=None, maxlength=None, sep=' ', doprint=None, output=False, **kwargs)[source]

Create a colorful heading. If just supplied with a string (or list of inputs like print()), create blue text with horizontal lines above and below and 3 spaces above. You can customize the color, the divider character, how many spaces appear before the heading, and the minimum length of the divider (otherwise will expand to match the length of the string, up to a maximum length).

Parameters
  • string (str) – the string to print as the heading (or object to convert to a string)

  • args (list) – additional strings to print

  • color (str) – color to use for the heading (default cyan)

  • divider (str) – symbol to use for the divider (default ‘—‘)

  • spaces (int) – number of spaces to put before the heading (default 3)

  • spacesafter (int) – number of spaces to put after the heading (default 1)

  • minlength (int) – minimum length of the divider (default 30)

  • maxlength (int) – maximum length of the divider (default 120)

  • sep (str) – if multiple arguments are supplied, use this separator to join them

  • doprint (bool) – whether to print the string (default true if no output)

  • output (bool) – whether to return the string as output (else, print)

  • kwargs (dict) – passed to sc.colorize()

Returns

Formatted string if output=True

Examples::

sc.heading(‘This is a heading’) sc.heading(string=’This is also a heading’, color=’red’, divider=’*’, spaces=0, minlength=50)

New in version 1.3.1.: “spacesafter”
printred(s, **kwargs)[source]

Alias to print(colors.red(s))

printyellow(s, **kwargs)[source]

Alias to print(colors.yellow(s))

printgreen(s, **kwargs)[source]

Alias to print(colors.green(s))

printcyan(s, **kwargs)[source]

Alias to print(colors.cyan(s))

printblue(s, **kwargs)[source]

Alias to print(colors.blue(s))

printmagenta(s, **kwargs)[source]

Alias to print(colors.magenta(s))

printv(string, thisverbose=1, verbose=2, newline=True, indent=True)[source]

Optionally print a message and automatically indent. The idea is that a global or shared “verbose” variable is defined, which is passed to subfunctions, determining how much detail to print out.

The general idea is that verbose is an integer from 0-4 as follows:

  • 0 = no printout whatsoever

  • 1 = only essential warnings, e.g. suppressed exceptions

  • 2 = standard printout

  • 3 = extra debugging detail (e.g., printout on each iteration)

  • 4 = everything possible (e.g., printout on each timestep)

Thus a very important statement might be e.g.

>>> sc.printv('WARNING, everything is wrong', 1, verbose)

whereas a much less important message might be

>>> sc.printv(f'This is timestep {i}', 4, verbose)

Version: 2016jan30

slacknotification(message=None, webhook=None, to=None, fromuser=None, verbose=2, die=False)[source]

Send a Slack notification when something is finished.

The webhook is either a string containing the webhook itself, or a plain text file containing a single line which is the Slack webhook. By default it will look for the file “.slackurl” in the user’s home folder. The webhook needs to look something like “https://hooks.slack.com/services/af7d8w7f/sfd7df9sb/lkcpfj6kf93ds3gj”. Webhooks are effectively passwords and must be kept secure! Alternatively, you can specify the webhook in the environment variable SLACKURL.

Parameters
  • message (str) – The message to be posted.

  • webhook (str) – See above

  • to (str) – The Slack channel or user to post to. Channels begin with #, while users begin with @ (note: ignored by new-style webhooks)

  • fromuser (str) – The pseudo-user the message will appear from (note: ignored by new-style webhooks)

  • verbose (bool) – How much detail to display.

  • die (bool) – If false, prints warnings. If true, raises exceptions.

Example:

sc.slacknotification('Long process is finished')
sc.slacknotification(webhook='/.slackurl', channel='@username', message='Hi, how are you going?')

What’s the point? Add this to the end of a very long-running script to notify your loved ones that the script has finished.

Version: 2018sep25

printtologfile(message=None, filename=None)[source]

Append a message string to a file specified by a filename name/path.

Note: in almost all cases, you are better off using Python’s built-in logging system rather than this function.

percentcomplete(step=None, maxsteps=None, stepsize=1, prefix=None)[source]

Display progress.

Example:

maxiters = 500
for i in range(maxiters):
    sc.percentcomplete(i, maxiters) # will print on every 5th iteration
    sc.percentcomplete(i, maxiters, stepsize=10) # will print on every 50th iteration
    sc.percentcomplete(i, maxiters, prefix='Completeness: ') # will print e.g. 'Completeness: 1%'
progressbar(i, maxiters, label='', every=1, length=30, empty='—', full='•', newline=False)[source]

Call in a loop to create terminal progress bar.

Parameters
  • i (int) – current iteration

  • maxiters (int) – maximum number of iterations (can also use an object with length)

  • label (str) – initial label to print

  • every (int/float) – if int, print every “every”th iteration (if 1, print all); if float and <1, print every maxiters*every iteration

  • length (int) – length of progress bar

  • empty (str) – character for not-yet-completed steps

  • full (str) – character for completed steps

  • newline (str) – character to print at the end of the line (default none)

Examples:

for i in range(20):
    sc.progressbar(i+1, 20)
    pl.pause(0.05)

x = np.arange(100)
for i in x:
    sc.progressbar(i+1, x, every=0.1)
    pl.pause(0.01)

Adapted from example by Greenstick (https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console)

New in version 1.3.3: “every” argument

class capture(seq='', *args, **kwargs)[source]

Captures stdout (e.g., from print()) as a variable.

Based on contextlib.redirect_stdout, but saves the user the trouble of defining and reading from an IO stream. Useful for testing the output of functions that are supposed to print certain output.

Examples:

# Using with...as
with sc.capture() as txt1:
    print('Assign these lines')
    print('to a variable')

# Using start()...stop()
txt2 = sc.capture().start()
print('This works')
print('the same way')
txt2.stop()

print('txt1:')
print(txt1)
print('txt2:')
print(txt2)

New in version 1.3.3.