Christopher Juckins

SysAdmin Tips, Tricks and other Software Tools

User Tools

Site Tools


python_code_snippets

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python_code_snippets [2020/09/08 18:55] juckinspython_code_snippets [2020/10/09 15:05] (current) juckins
Line 1: Line 1:
-==== Python code snippets ====+==== Python Coding Notes ====
  
 __Handling arguments__ __Handling arguments__
Line 22: Line 22:
 __Date and time strings__ __Date and time strings__
  
-[[https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes|See format codes]]+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   from datetime import datetime
Line 41: Line 41:
   if "Disruption".lower() in status.lower():   if "Disruption".lower() in status.lower():
     print('SD so exiting')     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
python_code_snippets.1599605755.txt.gz · Last modified: 2020/09/08 18:55 by juckins