Python

Notes

Python Debugger

Add the following line to start a debug session at that point in the code at runtime:

import pdb; pdb.set_trace() # Start debugging

Commands (hit enter to repeat previous command):

Dictionaries

Exceptions

Access ongoing Exception information: sys.exc_info():

Operators

Interaction with Operating System

Slicing

A step value can be used with any of the above: a[start:end:step].

The :end value represents the first value that is not in the selected slice. The difference between end and start is the number of elements selected (if step is 1, the default).

Also start or end may be a negative number, which means it counts from the end of the array instead of the beginning.

Python is forgiving if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error.

Recipes

Write File

import codecs
def write_file(filename, data):
    output_filepath = os.path.join(settings.PROJECT_DIR, filename)
    output_file = codecs.open(output_filepath, 'w', 'utf-8')
    output_file.write(data)
    output_file.close()
    print('Data written to %s' % (output_filepath))

Add to existing file: open(output_filepath, 'a', 'utf-8')

Remove Substring

  1. Find start of substring: start_pos = big_string.index('/home/')
  2. Find end of substring: end_pos = big_string.index("'",start_pos)
  3. Remove substring: big_string = big_string[:start_pos] + big_string[end_pos:]

To check if substring is present use: start_pos = big_string.find('/home/')

Display Progress Percentage

Calculate and display percentage progress:

rows = source_class.objects.using('legacy').all()
total = len(rows)
. . .
for i, row in enumerate(rows):
   . . .
   percent = float(i) / total * 100
   sys.stdout.write("\r%2.3f%%" % percent)
   sys.stdout.flush()

Example shows percentage to three decimal places, to show percentage as integer use "\r%2d%%".

Convert to HTML Entities

From Unicode: u'Østlandet'.encode('ascii', 'xmlcharrefreplace') gives 'Østlandet'.

From String: 'Østlandet'.decode('utf-8').encode('ascii', 'xmlcharrefreplace') also gives 'Østlandet'.