comparison cmd2.py @ 369:bc4b956d57b6

added run to py
author cat@eee
date Thu, 18 Feb 2010 16:13:10 -0500
parents 0816cdb5a7db
children 32b9137577b8
comparison
equal deleted inserted replaced
368:0816cdb5a7db 369:bc4b956d57b6
1014 1014
1015 def do_py(self, arg): 1015 def do_py(self, arg):
1016 ''' 1016 '''
1017 py <command>: Executes a Python command. 1017 py <command>: Executes a Python command.
1018 py: Enters interactive Python mode. 1018 py: Enters interactive Python mode.
1019 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`. 1019 End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, '`exit()``.
1020 Non-python commands can be issued with `cmd("your command")`. 1020 Non-python commands can be issued with ``cmd("your command")``.
1021 Run python code from external files with ``run("filename.py")``
1021 ''' 1022 '''
1022 self.pystate['self'] = self 1023 self.pystate['self'] = self
1023 arg = arg.parsed.raw[2:].strip() 1024 arg = arg.parsed.raw[2:].strip()
1025 localvars = (self.locals_in_py and self.pystate) or {}
1026 interp = InteractiveConsole(locals=localvars)
1027 interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')
1024 if arg.strip(): 1028 if arg.strip():
1025 interp = InteractiveInterpreter(locals=self.pystate)
1026 interp.runcode(arg) 1029 interp.runcode(arg)
1027 else: 1030 else:
1028 localvars = (self.locals_in_py and self.pystate) or {}
1029 interp = InteractiveConsole(locals=localvars)
1030 def quit(): 1031 def quit():
1031 raise EmbeddedConsoleExit 1032 raise EmbeddedConsoleExit
1032 def onecmd_plus_hooks(arg): 1033 def onecmd_plus_hooks(arg):
1033 return self.onecmd_plus_hooks(arg + '\n') 1034 return self.onecmd_plus_hooks(arg + '\n')
1035 def run(arg):
1036 try:
1037 file = open(arg)
1038 interp.runcode(file.read())
1039 file.close()
1040 except IOError, e:
1041 self.perror(e)
1034 self.pystate['quit'] = quit 1042 self.pystate['quit'] = quit
1035 self.pystate['exit'] = quit 1043 self.pystate['exit'] = quit
1036 self.pystate['cmd'] = onecmd_plus_hooks 1044 self.pystate['cmd'] = onecmd_plus_hooks
1045 self.pystate['run'] = run
1037 try: 1046 try:
1038 cprt = 'Type "help", "copyright", "credits" or "license" for more information.' 1047 cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
1039 keepstate = Statekeeper(sys, ('stdin','stdout')) 1048 keepstate = Statekeeper(sys, ('stdin','stdout'))
1040 sys.stdout = self.stdout 1049 sys.stdout = self.stdout
1041 sys.stdin = self.stdin 1050 sys.stdin = self.stdin