import argparsedefhello(args):print('Hello, {0}!'.format(args.name))defgoodbye(args):print('Goodbye, {0}!'.format(args.name))parser = argparse.ArgumentParser()subparsers = parser.add_subparsers()hello_parser = subparsers.add_parser('hello')hello_parser.add_argument('name')# add the name argumenthello_parser.set_defaults(func=hello)# set the default function to hellogoodbye_parser = subparsers.add_parser('goodbye')goodbye_parser.add_argument('name')goodbye_parser.set_defaults(func=goodbye)if__name__=='__main__': args = parser.parse_args() args.func(args)# call the default function
import click@click.group()defgreet():pass@greet.command()@click.argument('name')# add the name argumentdefhello(name):print(f'Hello, {name}!')@greet.command()@click.argument('name')defgoodbye(**kwargs):print(f'Goodbye, {kwargs["name"]}!')if__name__=='__main__':greet()
Simple cross-platform colored terminal text in Python
Makes ANSI escape character sequences (for producing colored terminal text and cursor positioning) work under MS Windows.
Colorama also provides some shortcuts to help generate ANSI sequences but works fine in conjunction with any other ANSI sequence generation library, such as the venerable Termcolor (https://pypi.org/project/termcolor/) or the fabulous Blessings (https://pypi.org/project/blessings/).
Possible color formattings:
🪄 Code:
from colorama import Fore, Back, Styleprint(Fore.YELLOW + Back.BLUE +'some yellow text')print(Back.GREEN +'and with a green background')print("Test..")print(Back.RED + Style.DIM +'and in dim text')# Check in console...print(Style.RESET_ALL)print('back to normal now')
📟 Output:
[33m[44msome yellow text
[42mand with a green background
Test..
[41m[2mand in dim text
[0m
back to normal now
delta = tomorrow - last_weekprint(f"In hours: {delta.hours}")print(delta.in_words(locale='en'))print(delta.in_words(locale='ru'))# <-- Only "ru" at the moment, no "ua" :(
📟 Output:
In hours: 23
1 week 23 hours 59 minutes 59 seconds
1 неделя 23 часа 59 минут 59 секунд
import sys# How to add a handler? How to set up logs formatting? How to filter messages? How to set level?# One answer: the add() function.logger.add(sys.stderr, format="{time}{level}{message}", filter="my_module", level="INFO")# Pretty formattinglogger.add(sys.stdout, colorize=True, format="<green>{time}</green> <level>{message}</level>")logger.debug("Check it now!")
📟 Output:
2019-09-20 13:09:10.415 | DEBUG | __main__:<module>:10 - Check it now!
[32m2019-09-20T13:09:10.415490+0000[0m [34m[1mCheck it now![0m
The code
logger.add("output.log", backtrace=True, diagnose=True)# Set 'False' to not leak sensitive data in proddeffunc(a,b):return a / bdefnested(c):try:func(5, c)exceptZeroDivisionError: logger.exception("What?!")nested(0)
will result in the following traceback debug log message:
2018-07-1701:38:43.975|ERROR|__main__:nested:10-What?!Traceback (most recentcalllast):File"test.py",line12,in<module>nested(0)└<functionnestedat0x7f5c755322f0>> File "test.py", line 8, in nestedfunc(5,c)│└0└<functionfuncat0x7f5c79fc2e18>File"test.py",line4,infuncreturna/b│└0└5ZeroDivisionError:divisionbyzero
from configobj import ConfigObjconfig =ConfigObj("config.ini")print(config['version'])# 0.1print(config['services'])# ["ui", "web", "db"]withopen(config['logging']['log_file'] as f: f.write(log_msg)
ConfigObj is a simple but powerful config file reader and writer: an ini file round tripper. Its main feature is that it is very easy to use, with a straightforward programmer’s interface and a simple syntax for config files. It has lots of other features though :
Nested sections (subsections), to any level
List values
Multiple line values
String interpolation (substitution)
Validation
Install as usual:
pipinstallconfigobj
Reading config
# As example let's read ini from "virtual" file:import ioini_contents ='''debug = Trueversion = 0.1services = ui, web, db, logging, web services[logging]log_level = INFOlog_file = /tmp/example.log'''f = io.StringIO(ini_contents)# File-like object
The profiling package is an interactive continuous Python profiler. It is inspired from Unity 3D profiler. This package provides these features:
> pip install profiling
Profiling statistics keep the frame stack.
An interactive TUI profiling statistics viewer.
Provides both of statistical and deterministic profiling.
Utilities for remote profiling.
Thread or greenlet aware CPU timer.
Supports Python 2.7, 3.3, 3.4 and 3.5.
Currently supports only Linux.
> profiling farm_unicorn.py
Requests
Requests is the only Non-GMO HTTP library for Python, safe for human consumption
Warning: Recreational use of other HTTP libraries may result in dangerous side-effects, including: security vulnerabilities, verbose code, reinventing the wheel, constantly reading documentation, depression, headaches, or even death.
import requestsendpoint ='https://catfact.ninja/facts?limit=5'r = requests.get(endpoint)print(r.status_code)#print(r.json())facts = r.json()['data']for f in facts:print(f"* {f['fact']}")
📟 Output:
200
* Unlike dogs, cats do not have a sweet tooth. Scientists believe this is due to a mutation in a key taste receptor.
* When a cat chases its prey, it keeps its head level. Dogs and humans bob their heads up and down.
* The technical term for a cat’s hairball is a “bezoar.”
* A group of cats is called a “clowder.”
* A cat can’t climb head first down a tree because every claw on a cat’s paw points the same way. To get down from a tree, a cat must back down.
JSON is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript.
JSON is built on two structures:
A collection of name/value pairs.
In Python it is dict.
An ordered list of values.
In Python it is list.
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.
A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.
json module
Python has json module which follows general API as other Python serialization modules
Load JSON and convert to Python base type object:
json.loads(json_str)
Save Python object as JSON string:
json.dumps(some_object)
🪄 Code:
import json
a = [1, 2, "hello man!", [34, 56.5]]
b = dict(a=1, b=3, c=[1,2,3, 'hello'])
print(json.dumps(a))
json.dumps(b)