def sighandler(signum, frame): '''Clean and tidy shutdown when killed.''' if po.opts.debug: ps_lib.msg('debug', 'Signal %s received.' % signum) #print 'removing:', readline.remove_history_item(readline.get_current_history_length()-1) # how to clear the line buffer? there doesn't seem to be a function to do it. print readline.redisplay() if signum == signal.SIGINT: sigintreceived = True
def getinput(): 'a generator function that returns a line or two from an interactive session.' previousline, line = '', '' isloop = False while True: if previousline: prompt = 'more> ' else: if po.color: prompt = ps_lib.eval_str(po.colorprompt) else: prompt = ps_lib.eval_str(po.prompt) ansi.xtermTitle(ps_lib.eval_str(po.title)) try: line = raw_input(prompt) # get input from user except EOFError: # sys.exit(1) or ^Z, ^D raise StopIteration break except KeyboardInterrupt: # ^C ( now caught earlier) print; continue if line.isspace(): line = '' # make sure blank line is false if not line and not previousline: continue # just an enter hit, I think # check if we need more input if line: if isloop: #previousline = previousline + ' ' + line + '\n' previousline = previousline + line + '\n' continue if line.split()[0] in pi.branch_words: #ps_lib. isloop = True previousline = previousline + line + '\n' continue if line[-1] == '\\': # get more previousline = previousline + line[:-1] continue else: # line is nada '', and a previous line exists, end extended line isloop = False if previousline: line = previousline + ' ' # keeep from triggering EOF downstream previousline = '' if po.opts.debug: ps_lib.msg('debug', `line`) if '\n' in line: for item in line.split('\n'): #print 'yielding:', `item` yield item #yield '' else: yield line
def interpret(linelist, namespace): '''This function takes a statement and processes it, replacing various syntax and variables with their values. The expanded statement is then returned. ''' po.wasunglobbed = False destlist = [] # destination for our processing # lets check each word for expansions for token in linelist: if po.opts.debug: ps_lib.msg('debug', 'token:%s' % token) # Brace expansion: echo sp{1,2,3}a > sp1a sp2a sp3a if '{' in token and '}' in token: token = ps_lib.expand_braces(token) if po.opts.debug: ps_lib.msg('debug', '{} exp:%s' % token) # tilde expansion if token[0] == '~': token = os.path.expanduser(token) if po.opts.debug: ps_lib.msg('debug', '~ exp:%s' % token) # check for any variables to expand '%var' if po.sym_expansion in token: token = ps_lib.expand_vars(token, po.namespace) # look for null args just expanded: if token == '\x00': token = '' # do command expansion in `...` if pi.sym_cmdsub in token: try: # here expand escape sequences. like removing quotes if po.sym_expansion in token: token = ps_lib.expand_escapes(token) token = ps_lib.cmd_substition(token) except NameError, why: # not found, halt all processing ps_lib.msg('error', str(why)) print return # more word splitting tokens = token.split() # check to see if it needs unglobbage for tokinho in tokens: globresults = ps_lib.unglob_token(tokinho) if globresults: # glob results probably don't need expansion, or they wouldnt work destlist = destlist + globresults # globs already list po.wasunglobbed = True else: # here expand escape sequences. like removing quotes if po.sym_expansion in tokinho: tokinho = ps_lib.expand_escapes(tokinho) destlist.append(tokinho)
def interpret(linelist, namespace): '''This function takes a statement and processes it, replacing various syntax and variables with their values. The expanded statement is then returned. ''' po.wasunglobbed = False destlist = [] # destination for our processing # lets check each word for expansions for token in linelist: if po.opts.debug: ps_lib.msg('debug', 'token:%s' % token) # Brace expansion: echo sp{1,2,3}a > sp1a sp2a sp3a if '{' in token and '}' in token: token = ps_lib.expand_braces(token) if po.opts.debug: ps_lib.msg('debug', '{} exp:%s' % token) # tilde expansion if token[0] == '~': token = os.path.expanduser(token) if po.opts.debug: ps_lib.msg('debug', '~ exp:%s' % token) # check for any variables to expand '%var' if po.sym_expansion in token: token = ps_lib.expand_vars(token, po.namespace) # look for null args just expanded: if token == '\x00': token = '' # do command expansion in `...` if pi.sym_cmdsub in token: try: # here expand escape sequences. like removing quotes if po.sym_expansion in token: token = ps_lib.expand_escapes(token) token = ps_lib.cmd_substition(token) except NameError, why: # not found, halt all processing ps_lib.msg('error', str(why)); print return # more word splitting tokens = token.split() # check to see if it needs unglobbage for tokinho in tokens: globresults = ps_lib.unglob_token(tokinho) if globresults: # glob results probably don't need expansion, or they wouldnt work destlist = destlist + globresults # globs already list po.wasunglobbed = True else: # here expand escape sequences. like removing quotes if po.sym_expansion in tokinho: tokinho = ps_lib.expand_escapes(tokinho) destlist.append(tokinho)
def getline(infile, mode='line'): for line in infile: if po.opts.debug: ps_lib.msg('debug', 'line:%r mode:=%s' % (line, mode) ) if mode == 'line': if line.isspace(): continue # blank line, continue else: if line.strip().startswith('#'): continue if not line: raise StopIteration # null line, EOF, break elif mode == 'block': if line: if line.isspace(): # blank line ends the block #print ' blank:%r' % line raise StopIteration else: #print ' grabbing line:%r' % line if line.strip().startswith('#'): continue yield line; continue else: raise StopIteration elif mode == 'skip': if line: if line.isspace(): raise StopIteration else: continue else: raise StopIteration line = line.rstrip() linelist = line.split() firstword = linelist[0] if linelist[0] in pi.branch_words: # evaluate branch # IF = if true, read and execute until branch ends if firstword == 'if': teststr = string.join(linelist[1:])[:-1] # ditch : #print 'debug test:{%s}' % test, #test = eval(teststr, po.namespace) try: test = eval(teststr, po.namespace) except Exception, why: ps_lib.msg('error', 'SyntaxError: ' + str(why)) if hasattr(infile, 'close'): raise StopIteration # if a real file stop for line in getline(infile, mode='skip'): pass continue if po.opts.debug: ps_lib.msg('debug', '%s (%s)' % (teststr, test) ) if test: getline(infile) else: for line in getline(infile, mode='skip'): pass elif firstword == 'while': teststr = string.join(linelist[1:])[:-1] # ditch : #print 'debug test:{%s}' % teststr, #test = eval(teststr, po.namespace) try: test = eval(teststr, po.namespace) except Exception, why: ps_lib.msg('error', 'SyntaxError: ' + str(why)) if hasattr(infile, 'close'): raise StopIteration # if a real file stop for line in getline(infile, mode='skip'): pass continue if po.opts.debug: ps_lib.msg('debug', '%s (%s)' % (teststr, test) ) if test: # get the block, and then exec block block = [] for line in getline(infile, mode='block'): block.append(line) #print 'debug: Block:', repr(block) break2 = False while test: #import time; time.sleep(1) for line in block: firstword = line.split()[0] if firstword == 'break': break2 = True break # get out yield line if break2: break test = eval(teststr, po.namespace) else: for line in getline(infile, mode='skip'): pass elif firstword == 'for': var, items = linelist[1], string.join(linelist[3:])[:-1] # ditch : # get the block, and then exec block block = [] for line in getline(infile, mode='block'): block.append(line) #print 'debug: Block:', repr(block) break2 = False try: for item in eval(items, po.namespace): po.namespace[var] = item for line in block: firstword = line.split()[0] if firstword == 'break': break2 = True break # get out yield line if break2: break except NameError, why: ps_lib.msg('error', 'NameError: ' + str(why)) if hasattr(infile, 'close'): raise StopIteration # if a real file stop
def __setattr__(self, name, value): ps_lib.msg('warning', 'The item %s cannot be changed.' % name) print
def complete(self, text, index): '''Return the next possible completion for 'text'. This function is called successively with index == 0, 1, 2, ... which returns each match until they run out and then returns None as a signal to readline to stop. ''' try: if index == 0: # on first call, find our matches self.matches = [] for kw in po.keywords: # try pyshell keywords if kw.startswith(text): self.matches.append(kw) for kw in keyword.kwlist: # python keywords if kw.startswith(text): self.matches.append(kw) if '.' in text: # python namespace # these need to check for nulls or be at end try: matches = self.attr_matches(text) except Exception: matches = None # which exception? if matches: self.matches += matches else: matches = self.global_matches(text) if matches: self.matches += matches # check where in the command line we are. necessary to # find out if we should search for executable or document. # This needs to take lines with multiple statements into account. start = readline.get_begidx(); pos = 0 if start == 0: # simple case findmode = 'executable' else: # if whitespace in front, find real start for i, char in enumerate(readline.get_line_buffer()): if char not in string.whitespace: pos = i; break if start == pos: findmode = 'executable' else: findmode = 'document' # else do document mode #then search filesystem # if text[0] == '~': # text = os.path.expanduser(text) if findmode == 'executable': if os.environ.has_key('PATH'): for folder in os.environ['PATH'].split(os.pathsep): matches = \ glob.glob(os.path.join(folder, text) + '*') #print matches for match in matches: self.matches += [os.path.basename(match)] else: self.matches += glob.glob(text + '*') else: # document matches = glob.glob(text + '*') for match in matches: if os.path.isdir(match): match = match + '/' self.matches += [match] if po.opts.debug: print; ps_lib.msg('debug', 'matches: %s' % self.matches) return self.matches[index] except IndexError: return None except Exception, why: print '\nps_completer err:', str(why) return None
'--faststart', action='store_true', dest='faststart', default=False, help='Do not execute startup files') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=True, help='Print extra information to the console') po.opts, po.args = parser.parse_args() if po.opts.debug: #ps_lib.msg('debug', 'ps_builtins namespace: %s' % po.keywords) ps_lib.msg('debug', 'command line: options=%s \nargs=%s' % (po.opts, po.args)) # Initialize some environment vars... os.environ['SHELL'] = sys.argv[0] # or maybe sys.executable os.environ['PWD'] = os.getcwd() # needed for default prompt on login shell import socket os.environ['HOSTNAME'] = socket.gethostname( ) # needed for prompt on login shell # some platform dependent code if sys.platform == 'win32': #os.system('cmd /c title %s' % ps_lib.eval_str(po.title)) # set title (doesnt work - reset on exit of cmd) pass readline = False
def complete(self, text, index): '''Return the next possible completion for 'text'. This function is called successively with index == 0, 1, 2, ... which returns each match until they run out and then returns None as a signal to readline to stop. ''' try: if index == 0: # on first call, find our matches self.matches = [] for kw in po.keywords: # try pyshell keywords if kw.startswith(text): self.matches.append(kw) for kw in keyword.kwlist: # python keywords if kw.startswith(text): self.matches.append(kw) if '.' in text: # python namespace # these need to check for nulls or be at end try: matches = self.attr_matches(text) except Exception: matches = None # which exception? if matches: self.matches += matches else: matches = self.global_matches(text) if matches: self.matches += matches # check where in the command line we are. necessary to # find out if we should search for executable or document. # This needs to take lines with multiple statements into account. start = readline.get_begidx() pos = 0 if start == 0: # simple case findmode = 'executable' else: # if whitespace in front, find real start for i, char in enumerate(readline.get_line_buffer()): if char not in string.whitespace: pos = i break if start == pos: findmode = 'executable' else: findmode = 'document' # else do document mode #then search filesystem # if text[0] == '~': # text = os.path.expanduser(text) if findmode == 'executable': if os.environ.has_key('PATH'): for folder in os.environ['PATH'].split(os.pathsep): matches = \ glob.glob(os.path.join(folder, text) + '*') #print matches for match in matches: self.matches += [os.path.basename(match)] else: self.matches += glob.glob(text + '*') else: # document matches = glob.glob(text + '*') for match in matches: if os.path.isdir(match): match = match + '/' self.matches += [match] if po.opts.debug: print ps_lib.msg('debug', 'matches: %s' % self.matches) return self.matches[index] except IndexError: return None except Exception, why: print '\nps_completer err:', str(why) return None
parser.add_option('-c', '--cmd', dest='command', #bogus help='Execute supplied command(s) and exit.', metavar='"echo foo"') parser.add_option('-d', '--debug', action='store_true', dest='debug', default=False, help='Print too much information to the console') parser.add_option('-f', '--faststart', action='store_true', dest='faststart', default=False, help='Do not execute startup files') parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=True, help='Print extra information to the console') po.opts, po.args = parser.parse_args() if po.opts.debug: #ps_lib.msg('debug', 'ps_builtins namespace: %s' % po.keywords) ps_lib.msg('debug', 'command line: options=%s \nargs=%s' % (po.opts, po.args) ) # Initialize some environment vars... os.environ['SHELL'] = sys.argv[0] # or maybe sys.executable os.environ['PWD'] = os.getcwd() # needed for default prompt on login shell import socket os.environ['HOSTNAME'] = socket.gethostname() # needed for prompt on login shell # some platform dependent code if sys.platform == 'win32': #os.system('cmd /c title %s' % ps_lib.eval_str(po.title)) # set title (doesnt work - reset on exit of cmd) pass readline = False elif os.name == 'posix':
def getline(infile, mode='line'): for line in infile: if po.opts.debug: ps_lib.msg('debug', 'line:%r mode:=%s' % (line, mode)) if mode == 'line': if line.isspace(): continue # blank line, continue else: if line.strip().startswith('#'): continue if not line: raise StopIteration # null line, EOF, break elif mode == 'block': if line: if line.isspace(): # blank line ends the block #print ' blank:%r' % line raise StopIteration else: #print ' grabbing line:%r' % line if line.strip().startswith('#'): continue yield line continue else: raise StopIteration elif mode == 'skip': if line: if line.isspace(): raise StopIteration else: continue else: raise StopIteration line = line.rstrip() linelist = line.split() firstword = linelist[0] if linelist[0] in pi.branch_words: # evaluate branch # IF = if true, read and execute until branch ends if firstword == 'if': teststr = string.join(linelist[1:])[:-1] # ditch : #print 'debug test:{%s}' % test, #test = eval(teststr, po.namespace) try: test = eval(teststr, po.namespace) except Exception, why: ps_lib.msg('error', 'SyntaxError: ' + str(why)) if hasattr(infile, 'close'): raise StopIteration # if a real file stop for line in getline(infile, mode='skip'): pass continue if po.opts.debug: ps_lib.msg('debug', '%s (%s)' % (teststr, test)) if test: getline(infile) else: for line in getline(infile, mode='skip'): pass elif firstword == 'while': teststr = string.join(linelist[1:])[:-1] # ditch : #print 'debug test:{%s}' % teststr, #test = eval(teststr, po.namespace) try: test = eval(teststr, po.namespace) except Exception, why: ps_lib.msg('error', 'SyntaxError: ' + str(why)) if hasattr(infile, 'close'): raise StopIteration # if a real file stop for line in getline(infile, mode='skip'): pass continue if po.opts.debug: ps_lib.msg('debug', '%s (%s)' % (teststr, test)) if test: # get the block, and then exec block block = [] for line in getline(infile, mode='block'): block.append(line) #print 'debug: Block:', repr(block) break2 = False while test: #import time; time.sleep(1) for line in block: firstword = line.split()[0] if firstword == 'break': break2 = True break # get out yield line if break2: break test = eval(teststr, po.namespace) else: for line in getline(infile, mode='skip'): pass elif firstword == 'for': var, items = linelist[1], string.join( linelist[3:])[:-1] # ditch : # get the block, and then exec block block = [] for line in getline(infile, mode='block'): block.append(line) #print 'debug: Block:', repr(block) break2 = False try: for item in eval(items, po.namespace): po.namespace[var] = item for line in block: firstword = line.split()[0] if firstword == 'break': break2 = True break # get out yield line if break2: break except NameError, why: ps_lib.msg('error', 'NameError: ' + str(why)) if hasattr(infile, 'close'): raise StopIteration # if a real file stop