Back Home

Setting up Local Environments

pip install virtualenv

to create a virtualenv envrionment

virtualenv -p /c/Python27/python <folder>

Try/Catch

try:
    open('/path/to/does/not/exist', 'rb')
except (SystemExit, KeyboardInterrupt):
    raise
except Exception, e:
    logger.error('Failed to open file', exc_info=True)

Logging

python supports a standard logging framework:

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

Setting the logging configuraiton:

import logging
 
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
 
# create a file handler
 
handler = logging.FileHandler('hello.log')
handler.setLevel(logging.INFO)
 
# create a logging format
 
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
 
# add the handlers to the logger
 
logger.addHandler(handler)
 
logger.info('Hello baby')

Logging Config via ini File

Logging code to import config:

import logging
 
# load my module
 
import my_module
 
# load the logging configuration
 
logging.config.fileConfig('logging.ini')
 
my_module.foo()
bar = my_module.Bar()
bar.bar()

The logging.ini file can look like:

[loggers]
keys=root
 
[handlers]
keys=consoleHandler
 
[formatters]
keys=simpleFormatter
 
[logger_root]
level=DEBUG
handlers=consoleHandler
 
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
 
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

Static Typing - MyPy

http://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/

def sum_and_stringify(nums: List[int]) -> str:  
    """Adds up the numbers in a list and returns the result as a string."""
    return str(sum(nums))
 
python.txt · Last modified: 2016/10/17 02:16 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd