Christopher Juckins

SysAdmin Tips, Tricks and other Software Tools

User Tools

Site Tools


python_code_snippets

Python Coding Notes

Handling arguments

import argparse

parser = argparse.ArgumentParser(description='Collect arguments')
parser.add_argument("-t", required=True, type=str, help="Train number")
parser.add_argument("-s", required=True, type=str, help="Station")
parser.add_argument("-d", required=True, type=str, help="Date")

args = parser.parse_args()

train_num = args.t
station = args.s
date = args.d

print(train_num)
print(station)
print(date)

Date and time strings

See format codes here and here

from datetime import datetime

date_time_str = '2020-09-07T00:27:00-04:00'
date_time_str = date_time_str[:-6]
date_time_obj = datetime.strptime(date_time_str, '%Y-%m-%dT%H:%M:%S')
#print("The type of the date is now",  type(date_time_obj))
#print("The date is", date_time_obj)
date_time_str_format = date_time_obj.strftime('%I:%M %P')
print(date_time_str_format)

Checking and matching stuff in strings

String Matches

status = "Service disruption"
if "Disruption".lower() in status.lower():
  print('SD so exiting')
  

Writing to files

See file handling tips

outputFileName = 'status_out_' + train_num + '_' + station + '.txt'
outputFile = open(outputFileName, 'w')
print(url, file=outputFile)
outputFile.close

Logging

Logging in python

logging.basicConfig(format='%(asctime)s %(message)s', filename=log_file, level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

Write beautiful python code with PEP-8

Working with JSON

  • Use PyPi dictor
  • Use PyPi (from demjson which includes JSON Lint to check for valid JSON code and make fixes
    • sudo pip install demjson
    • installs into /usr/local/bin/jsonlint
    • jsonlint data.json
    • jsonlint –help
python_code_snippets.txt · Last modified: 2020/10/09 15:05 by juckins