Package pyforms :: Package terminal :: Module BaseWidget |
[hide private]
[frames] | no frames]

# Source Code for Module pyforms.terminal.BaseWidget

      1  from pyforms.Controls import ControlFile, ControlSlider, ControlText, ControlCombo, ControlCheckBox, ControlBase, ControlDir
      2  from datetime import datetime, timedelta
      3  import argparse, uuid, os, shutil, time, sys, subprocess
      4
      5  try:
      6          import requests
      7  except:
      8          print "No requests lib"
      9
     10
     11 -class BaseWidget(object):
     12
     13
     14
     15 -        def __init__(self, title):
     16                  self._parser = argparse.ArgumentParser()
     17                  f = open('pid.txt', 'w')
     18                  f.write(str(os.getpid()))
     19                  f.close()
     20
     21                  self._controlsPrefix    = ''
     22                  self._title                     = title
     23                  self.stop                               = False
     24
     25          ############################################################################
     26          ############ Module functions  #############################################
     27          ############################################################################
     28
     29 -        def initForm(self, parse=True):
     30                  result = {}
     31                  for fieldname, var in self.formControls.items():
     32                          name = var._name
     33                          if isinstance(var, (ControlFile,ControlSlider,ControlText, ControlCombo,ControlCheckBox, ControlDir) ):
     34                                  self._parser.add_argument("--%s" % name, help=var.label)
     35
     36                  if parse:
     37
     38                          self._parser.add_argument(
     39                                  "--exec{0}".format(self._controlsPrefix),
     40                                  default='',
     41                                  help='Function from the application that should be executed. Use | to separate a list of functions.')
     42                          self._args = self._parser.parse_args()
     43
     44                          self.parseTerminalParameters()
     45                          self.executeEvents()
     46
     47
     48 -        def parseTerminalParameters(self):
     49                  for fieldname, var in self.formControls.items():
     50                          name = var._name
     51                          if self._args.__dict__.get(name, None):
     52
     53                                  if isinstance(var, ControlFile):
     54                                          value = self._args.__dict__[name]
     55                                          if value!=None and (value.startswith('http://') or value.startswith('https://')):
     56                                                  local_filename = value.split('/')[-1]
     57                                                  outputFileName = os.path.join('input', local_filename)
     58                                                  self.__downloadFile(value, outputFileName)
     59                                                  var.value = outputFileName
     60                                          else:
     61                                                  var.value = value
     62
     63                                  if isinstance(var, ControlDir):
     64                                          value = self._args.__dict__[name]
     65                                          var.value = value
     66
     67                                  elif isinstance(var,  (ControlText, ControlCombo)):
     68                                          var.value = self._args.__dict__[name]
     69                                  elif isinstance(var, ControlCheckBox):
     70                                          var.value = self._args.__dict__[name]=='True'
     71                                  elif isinstance(var, ControlSlider):
     72                                          var.value = int(self._args.__dict__[name])
     73
     74
     75
     76 -        def executeEvents(self):
     77                  for function in self._args.__dict__.get("exec{0}".format(self._controlsPrefix), []).split('|'):
     78                          if len(function)>0: getattr(self, function)()
     79
     80                  res = {}
     81                  for controlName, control in self.formControls.items(): res[controlName] = control.value
     82                  outfile = open('out-parameters.txt', 'wb')
     83                  outfile.write( str(res) )
     84                  outfile.close()
     85
     86
     87 -        def __downloadFile(self, url, outFilepath):
     88                  chunksize = 512*1024
     89                  r = requests.get(url, stream=True)
     90                  with open(outFilepath, 'wb') as f:
     91                          for chunk in r.iter_content(chunk_size=chunksize):
     92                                  if chunk: f.write(chunk); f.flush();
     93
     94
     95
     96 -        def execute(self): pass
     97
     98
     99 -        def start_progress(self, total = 100):
    100                  self._total_processing_count = total
    101                  self._processing_initial_time = time.time()
    102                  self._processing_count  = 1
    103
    104 -        def update_progress(self):
    105                  div = int(self._total_processing_count/400)
    106                  if div==0: div = 1
    107                  if (self._processing_count % div )==0:
    108                          self._processing_last_time = time.time()
    109                          total_passed_time = self._processing_last_time - self._processing_initial_time
    110                          remaining_time = ( (self._total_processing_count * total_passed_time) / self._processing_count ) - total_passed_time
    111                          if remaining_time<0: remaining_time = 0
    112                          time_remaining = datetime(1,1,1) + timedelta(seconds=remaining_time )
    113                          time_elapsed = datetime(1,1,1) + timedelta(seconds=(total_passed_time) )
    114
    115                          values = (
    116                                                  time_elapsed.day-1,  time_elapsed.hour, time_elapsed.minute, time_elapsed.second,
    117                                                  time_remaining.day-1, time_remaining.hour, time_remaining.minute, time_remaining.second,
    118                                                  (float(self._processing_count)/float(self._total_processing_count))*100.0, self._processing_count, self._total_processing_count,
    119                                          )
    120
    121                          print "Elapsed: %d:%d:%d:%d; Remaining: %d:%d:%d:%d; Processed %0.2f %%  (%d/%d); |   \r" % values,
    122                          sys.stdout.flush()
    123
    124                  self._processing_count  += 1
    125
    126 -        def end_progress(self):
    127                  self._processing_count = self._total_processing_count
    128                  self.update_progress()
    129
    130
    131
    132 -        def __savePID(self, pid):
    133                  try:
    134                          with open('pending_PID.txt', 'w') as f:
    135                                  f.write(str(pid))
    136                                  f.write('\n')
    137                  except (IOError) as e:
    138                          raise e
    139
    140 -        def __savePID(self, pid):
    141                  try:
    142                          with open('pending_PID.txt', 'w') as f:
    143                                  f.write(str(pid))
    144                                  f.write('\n')
    145                  except (IOError) as e:
    146                          raise e
    147
    148 -        def executeCommand(self, cmd, cwd=None):
    149                  if cwd!=None:
    150                          currentdirectory = os.getcwd()
    151                          os.chdir(cwd)
    152
    153                  print " ".join(cmd)
    154                  proc = subprocess.Popen(cmd)
    155
    156                  if cwd!=None: os.chdir(currentdirectory)
    157                  self.__savePID(proc.pid)
    158                  proc.wait()
    159                  #(output, error) = proc.communicate()
    160                  #if error: print 'error: ', error
    161                  #print 'output: ', output
    162                  return ''#output
    163
    164
    165
    166          @property
    167 -        def formControls(self):
    168                  """
    169                  Return all the form controls from the the module
    170                  """
    171                  result = {}
    172                  for name, var in vars(self).items():
    173                          if isinstance(var, ControlBase):
    174                                  var._name = self._controlsPrefix+"-"+name if len(self._controlsPrefix)>0 else name
    175                                  result[name] = var
    176                  return result
    177