template.py #1

  • //
  • guest/
  • perforce_software/
  • sdp/
  • main/
  • Server/
  • Unix/
  • p4/
  • common/
  • bin/
  • templates/
  • template.py
  • View
  • Commits
  • Open Download .zip Download (4 KB)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""@template.py PythonScriptTemplate
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
#------------------------------------------------------------------------------
template.py - Python script template.  EDITME

"""

# Python 2.7/3.3 compatibility.
from __future__ import print_function

import sys

# Python 2.7/3.3 compatibility.
if sys.version_info[0] >= 3:
   from configparser import ConfigParser
else:
   from ConfigParser import ConfigParser

import argparse
import textwrap
import os.path
from datetime import datetime
import logging

DEFAULT_CFG_FILE='template.py.cfg'
DEFAULT_LOG_FILE='template.log'
DEFAULT_VERBOSITY='INFO'

LOGGER_NAME = 'template.py'
DEFAULTS_SECTION = 'Defaults'

class Main:
   """ EDITME Documentation for MyClass.
   EDITME
   """

   def __init__(self, *argv):
      """ Initialization.  Process command line argument and initialize logging.
      """
      parser = argparse.ArgumentParser(
         formatter_class=argparse.RawDescriptionHelpFormatter,
         description=textwrap.dedent('''\
            NAME
         
            template.py
            
            VERSION
            
            1.0.0
            
            DESCRIPTION
            
            EDITME - Describe this script.
            
            EXAMPLES
            
            EXIT CODES
            
            Zero indicates normal completion.  Non-zero indicates an error.
            
            '''),
         epilog="Copyright (c) 2008-2015 Perforce Software, Inc.  Provided for use as defined in the Perforce Consulting Services Agreement."
      )
      
      parser.add_argument('first', help="First positional arg.")
      parser.add_argument('second', help="Second positional arg.")
      #parser.add_argument('-r', '--reqarg', nargs='?', action='store_true', required=True, help="Sample required \(positional\) argument.")
      parser.add_argument('-n', '--NoOp', action='store_true', help="Take no actions that affect data (\"No Operation\").")
      parser.add_argument('-c', '--config', default=DEFAULT_CFG_FILE, help="Config file, relative or absolute path. Default: " + DEFAULT_CFG_FILE)
      parser.add_argument('-L', '--log', default=DEFAULT_LOG_FILE, help="Default: " + DEFAULT_LOG_FILE)
      parser.add_argument('-v', '--verbosity', 
         nargs='?', 
         const="INFO",
         default=DEFAULT_VERBOSITY,
         choices=('DEBUG', 'WARNING', 'INFO', 'ERROR', 'FATAL') ,
         help="Output verbosity level. Default is: " + DEFAULT_VERBOSITY)
      
      self.myOptions = parser.parse_args()
      
      self.logger = logging.getLogger(LOGGER_NAME)
      self.logger.setLevel(self.myOptions.verbosity)
      h = logging.StreamHandler()
      # df = datestamp formatter; bf= basic formatter.
      df = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
      bf = logging.Formatter('%(levelname)s: %(message)s')
      h.setFormatter(bf)
      self.logger.addHandler (h)

      self.logger.debug ("Command Line Options: %s\n" % self.myOptions)
      
      if (self.myOptions.NoOp):
         self.logger.info ("Running in NO OP mode.")

   def readConfig(self):
      self.parser = ConfigParser()
      self.myOptions.parser = self.parser    # for later use

      try:
         self.parser.readfp(open(self.myOptions.config))

      except:
         self.logger.warn ('Could not read config file [%s].  Ignoring it.' % self.myOptions.config)
         return False

      if self.parser.has_section(DEFAULTS_SECTION):
         if self.parser.has_option(DEFAULTS_SECTION, "MyVar"):
            myVar = self.parser.get(DEFAULTS_SECTION, "MyVar")
            self.logger.debug ('MyVar value is [%s].' % myVar)
            self.logger.debug ('Loaded data from config file [%s].' % self.myOptions.config)
      else:
         self.logger.fatal ('No [%s] section in config file.  Aborting.' % DEFAULTS_SECTION)
         return False

      return True
      

   def sample(self):
      """Sample Method"""
      self.readConfig()

      self.logger.info ("Processing...")

if __name__ == '__main__':
   """ Main Program
   """
   main = Main(*sys.argv[1:])
   Main.sample(main)
# Change User Description Committed
#1 27331 C. Thomas Tyler Released SDP 2020.1.27325 (2021/01/29).
Copy Up using 'p4 copy -r -b perforce_software-sdp-dev'.
//guest/perforce_software/sdp/dev/Server/Unix/p4/common/bin/templates/template.py
#1 26745 Robert Cowham Create templates sub=folder to tidy up /p4/common/bin
//guest/perforce_software/sdp/dev/Server/Unix/p4/common/bin/template.py
#3 16029 C. Thomas Tyler Routine merge to dev from main using:
p4 merge -b perforce_software-sdp-dev
#2 12169 Russell C. Jackson (Rusty) Updated copyright date to 2015

 Updated shell scripts to require an instance parameter to eliminate the need
 for calling p4master_run.    Python and Perl still need it since you have to set the
environment for them to run in.

 Incorporated comments from reviewers. Left the . instead of source as that seems
more common in the field and has the same functionality.
#1 10638 C. Thomas Tyler Populate perforce_software-sdp-dev.
//guest/perforce_software/sdp/main/Server/Unix/p4/common/bin/template.py
#1 10148 C. Thomas Tyler Promoted the Perforce Server Deployment Package to The Workshop.