diff options
| author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2017-01-11 17:04:08 -0500 |
|---|---|---|
| committer | Todd Leonhardt <todd.leonhardt@gmail.com> | 2017-01-11 17:04:08 -0500 |
| commit | d21e6ae899b9ac8c53178946675ed7ca80af084a (patch) | |
| tree | 0d69eb5858ad6276ae89b136b081b46e0b32392c | |
| parent | 30e55d72351b367a1c303cc1d52c2bfaf950ccec (diff) | |
| download | cmd2-git-d21e6ae899b9ac8c53178946675ed7ca80af084a.tar.gz | |
For do_py(), moved the definition of the run() command earlier.
This is so that it will allow the user to run a Python script directly from the Cmd prompt even before an interactive Python shell has ever been invoked via:
py run('script.py')
This fixes a bug where it wouldn't allow that to occur until the user entered just "py" at the Cmd prompt.
Also added a trivial Python script script.py to the example directory for the purposes of testing script execution.
| -rwxr-xr-x | cmd2.py | 20 | ||||
| -rw-r--r-- | example/script.py | 3 |
2 files changed, 14 insertions, 9 deletions
@@ -1130,9 +1130,20 @@ class Cmd(cmd.Cmd): ''' self.pystate['self'] = self arg = arg.parsed.raw[2:].strip() + + # Support the run command even if called prior to invoking an interactive interpreter + def run(arg): + try: + with open(arg) as f: + interp.runcode(f.read()) + except IOError as e: + self.perror(e) + self.pystate['run'] = run + localvars = (self.locals_in_py and self.pystate) or {} interp = InteractiveConsole(locals=localvars) interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())') + if arg.strip(): interp.runcode(arg) else: @@ -1142,18 +1153,9 @@ class Cmd(cmd.Cmd): def onecmd_plus_hooks(arg): return self.onecmd_plus_hooks(arg + '\n') - def run(arg): - try: - file = open(arg) - interp.runcode(file.read()) - file.close() - except IOError as e: - self.perror(e) - self.pystate['quit'] = quit self.pystate['exit'] = quit self.pystate['cmd'] = onecmd_plus_hooks - self.pystate['run'] = run keepstate = None try: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' diff --git a/example/script.py b/example/script.py new file mode 100644 index 00000000..7d0c998a --- /dev/null +++ b/example/script.py @@ -0,0 +1,3 @@ +#!/usr/bin/env python +print("This is a python script running ...") + |
