Example #1
0
def bkgdProcess(commandArr, outfile=None, errfile='stdout', returnOnErr=False):
    """bkgdProcess(commandArr, [outfile] [, errfile]) - Run a process in background
   with optional redirection of standard output to a file, and of standard error
   to a separate file or to standard out by default.
   """
    try:

        # If subprocess is allowed, open the files if any
        if useSubprocess:
            outf = None
            errf = None
            errToFile = False
            if errfile == 'stdout':
                errf = STDOUT
            if outfile:
                action = 'Opening ' + outfile + ' for output'
                outf = open(outfile, 'w')
                errToFile = errfile == 'stdout'
            if errfile and errfile != 'stdout':
                action = 'Opening ' + errfile + ' for output'
                errf = open(errfile, 'w')
                errToFile = True

            # Use detached flag on Windows, although it may not be needed
            # In fact, unless stderr is going to a file it keeps it from running there
            action = 'Starting background process ' + commandArr[0]
            if sys.platform.find('win32') >= 0 and errToFile:
                DETACHED_PROCESS = 0x00000008
                Popen(commandArr,
                      shell=False,
                      stdout=outf,
                      stderr=errf,
                      creationflags=DETACHED_PROCESS)
            else:
                Popen(commandArr, shell=False, stdout=outf, stderr=errf)
            return None

        # Otherwise use system call: wrap all args in quotes and add the redirects
        comstr = commandArr[0]
        action = 'Starting background process ' + commandArr[0]
        for i in range(1, len(commandArr)):
            comstr += ' "' + commandArr[i] + '"'
        if outfile:
            comstr += ' > "' + outfile + '"'
        if errfile == 'stdout':
            comstr += ' 2>&1'
        elif errfile:
            comstr += ' 2> "' + errfile + '"'
        comstr += ' &'

        # The return value is not useful when it fails to run
        os.system(comstr)
        return None

    except Exception:
        errString = action + "  - " + str(sys.exc_info()[1])
        if returnOnErr:
            return errString
        exitError(errString)
Example #2
0
def bkgdProcess(commandArr, outfile=None, errfile='stdout', returnOnErr = False):
   """bkgdProcess(commandArr, [outfile] [, errfile]) - Run a process in background
   with optional redirection of standard output to a file, and of standard error
   to a separate file or to standard out by default.
   """
   try:

      # If subprocess is allowed, open the files if any
      if useSubprocess:
         outf = None
         errf = None
         errToFile = False
         if errfile == 'stdout':
            errf = STDOUT
         if outfile:
            action = 'Opening ' + outfile + ' for output'
            outf = open(outfile, 'w')
            errToFile = errfile == 'stdout'
         if errfile and errfile != 'stdout':
            action = 'Opening ' + errfile + ' for output'
            errf = open(errfile, 'w')
            errToFile = True

         # Use detached flag on Windows, although it may not be needed
         # In fact, unless stderr is going to a file it keeps it from running there
         action = 'Starting background process ' + commandArr[0]
         if sys.platform.find('win32') >= 0 and errToFile:
            DETACHED_PROCESS = 0x00000008
            Popen(commandArr, shell=False, stdout=outf, stderr=errf,
                  creationflags=DETACHED_PROCESS)
         else:
            Popen(commandArr, shell=False, stdout=outf, stderr=errf)
         return None

      # Otherwise use system call: wrap all args in quotes and add the redirects
      comstr = commandArr[0]
      action = 'Starting background process ' + commandArr[0]
      for i in range(1, len(commandArr)):
         comstr += ' "' + commandArr[i] + '"'
      if outfile:
         comstr += ' > "' + outfile + '"'
      if errfile == 'stdout':
         comstr += ' 2>&1'
      elif errfile:
         comstr += ' 2> "' + errfile + '"'
      comstr += ' &'

      # The return value is not useful when it fails to run
      os.system(comstr)
      return None
         
   except Exception:
      errString = action + "  - " + str(sys.exc_info()[1])
      if returnOnErr:
         return errString
      exitError(errString)
Example #3
0
def readTextFile(filename, descrip=None, returnOnErr=False, maxLines=None):
    """readTextFile(filename[ , descrip])  - read in text file, strip endings

   Reads in the text file in <filename> if this is a string, or reads from it
   as an open file object if not, strips the line endings and blanks
   from the end of each line, and returns a list of strings.  If maxLines is 
   passed, then it reads up to that number of lines.  Exits with
   exitError on an error opening or reading the file, and adds the optional
   description in <descrip> to the error message.  Or, if returnOnErr is True,
   it returns the error string itself.
   """
    if not descrip:
        descrip = " "
    try:
        errString = "Opening"
        if isinstance(filename, str):
            textfile = open(filename, 'r')
        else:
            textfile = filename
        errString = "Reading"
        if maxLines:
            lines = []
            for ind in range(maxLines):
                line = textfile.readline()
                if not line:
                    break
                lines.append(line)
        else:
            lines = textfile.readlines()

    except IOError:
        errString = fmtstr("{} {} {}: {}", errString, descrip, filename, \
                         str(sys.exc_info()[1]))
        if returnOnErr:
            try:
                textfile.close()
            except:
                pass
            return errString
        exitError(errString)

    textfile.close()
    for i in range(len(lines)):
        lines[i] = lines[i].rstrip(' \t\r\n')
    return lines
Example #4
0
def readTextFile(filename, descrip = None, returnOnErr = False, maxLines = None):
   """readTextFile(filename[ , descrip])  - read in text file, strip endings

   Reads in the text file in <filename> if this is a string, or reads from it
   as an open file object if not, strips the line endings and blanks
   from the end of each line, and returns a list of strings.  If maxLines is 
   passed, then it reads up to that number of lines.  Exits with
   exitError on an error opening or reading the file, and adds the optional
   description in <descrip> to the error message.  Or, if returnOnErr is True,
   it returns the error string itself.
   """
   if not descrip:
      descrip = " "
   try:
      errString = "Opening"
      if isinstance(filename, str):
         textfile = open(filename, 'r')
      else:
         textfile = filename
      errString = "Reading"
      if maxLines:
         lines = []
         for ind in range(maxLines):
            line = textfile.readline()
            if not line:
               break
            lines.append(line)
      else:
         lines = textfile.readlines()

   except IOError:
      errString = fmtstr("{} {} {}: {}", errString, descrip, filename, \
                       str(sys.exc_info()[1]))
      if returnOnErr:
         try:
            textfile.close()
         except:
            pass
         return errString
      exitError(errString)

   textfile.close()
   for i in range(len(lines)):
      lines[i] = lines[i].rstrip(' \t\r\n')
   return lines
Example #5
0
def completeAndCheckComFile(comfile):
    """completeAndCheckComFile(comfile) - return complete com file name and root
   Given a com file file name that can be file, file., or file.com, compose
   the complete name and the root name and exit with error if file does not
   exist.
   """
    if not comfile:
        exitError("A command file must be entered")

    if comfile.endswith('.com'):
        rootname = comfile[0:len(comfile) - 4]
    elif comfile.endswith('.'):
        rootname = comfile.rstrip('.')
    else:
        rootname = comfile

    comfile = rootname + '.com'
    if not os.path.exists(comfile):
        exitError("Command file " + comfile + " does not exist")
    return (comfile, rootname)
Example #6
0
def completeAndCheckComFile(comfile):
   """completeAndCheckComFile(comfile) - return complete com file name and root
   Given a com file file name that can be file, file., or file.com, compose
   the complete name and the root name and exit with error if file does not
   exist.
   """
   if not comfile:
      exitError("A command file must be entered")

   if comfile.endswith('.com'):
      rootname = comfile[0 : len(comfile) - 4]
   elif comfile.endswith('.'):
      rootname = comfile.rstrip('.')
   else:
      rootname = comfile

   comfile = rootname + '.com'
   if not os.path.exists(comfile):
      exitError("Command file " + comfile + " does not exist")
   return (comfile, rootname)
Example #7
0
def writeTextFile(filename, strings, returnOnErr = False):
   """writeTextFile(filename, strings) - write set of strings to a text file
   Opens the file <filename> and writes the set of strings in the list
   <strings>, adding a line ending to each.  Exits with exitError upon error,
   or returns an error string if returnOnErr is True.
   """
   try:
      action = 'Opening'
      comf = open(filename, 'w')
      action = 'Writing to'
      for line in strings:
         prnstr(line, file=comf)
      comf.close()
   except IOError:
      errString = action + " file: " + filename + "  - " + str(sys.exc_info()[1])
      if returnOnErr:
         try:
            comf.close()
         except:
            pass
         return errString
      exitError(errString)
Example #8
0
def convertToInteger(valstr, description):
    try:
        return int(valstr)
    except ValueError:
        exitError('Converting ' + description + ' (' + valstr + ') to integer')
Example #9
0
def convertToInteger(valstr, description):
   try:
      return int(valstr)
   except ValueError:
      exitError('Converting ' + description + ' (' + valstr + ') to integer')