==== 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 [[https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes|here]] and [[https://strftime.org/|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__ [[https://thispointer.com/python-check-if-a-string-contains-a-sub-string-find-its-index-case-insensitive/|String Matches]] status = "Service disruption" if "Disruption".lower() in status.lower(): print('SD so exiting') __Writing to files__ [[https://www.geeksforgeeks.org/how-to-open-and-close-a-file-in-python/|See file handling tips]] outputFileName = 'status_out_' + train_num + '_' + station + '.txt' outputFile = open(outputFileName, 'w') print(url, file=outputFile) outputFile.close __Logging__ [[https://docs.python.org/3/howto/logging.html|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') [[https://realpython.com/python-pep8/|Write beautiful python code with PEP-8]] __Working with JSON__ * Use PyPi [[https://pypi.org/project/dictor/|dictor]] * Use PyPi (from [[https://pypi.org/project/demjson/|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