Johnny Chen | de6ade0 | 2011-10-12 19:16:06 +0000 | [diff] [blame] | 1 | """Utility for changing directories and execution of commands in a subshell.""" |
| 2 | |
| 3 | import os, shlex, subprocess |
| 4 | |
Johnny Chen | 7596f93 | 2011-10-13 01:20:34 +0000 | [diff] [blame^] | 5 | # Store the previous working directory for the 'cd -' command. |
| 6 | class Holder: |
| 7 | """Holds the _prev_dir_ class attribute for chdir() function.""" |
| 8 | _prev_dir_ = None |
| 9 | |
| 10 | @classmethod |
| 11 | def prev_dir(cls): |
| 12 | return cls._prev_dir_ |
| 13 | |
| 14 | @classmethod |
| 15 | def swap(cls, dir): |
| 16 | cls._prev_dir_ = dir |
| 17 | |
Johnny Chen | de6ade0 | 2011-10-12 19:16:06 +0000 | [diff] [blame] | 18 | def chdir(debugger, args, result, dict): |
Johnny Chen | 7596f93 | 2011-10-13 01:20:34 +0000 | [diff] [blame^] | 19 | """ |
| 20 | Change the working directory, or cd to ${HOME}. |
| 21 | You can also issue 'cd -' to change to the previous working directory. |
| 22 | """ |
| 23 | new_dir = args.strip() |
| 24 | if not new_dir: |
| 25 | new_dir = os.path.expanduser('~') |
| 26 | elif new_dir == '-': |
| 27 | if not Holder.prev_dir(): |
| 28 | # Bad directory, not changing. |
| 29 | print "bad directory, not changing" |
| 30 | return |
| 31 | else: |
| 32 | new_dir = Holder.prev_dir() |
| 33 | |
| 34 | Holder.swap(os.getcwd()) |
| 35 | os.chdir(new_dir) |
Johnny Chen | de6ade0 | 2011-10-12 19:16:06 +0000 | [diff] [blame] | 36 | print "Current working directory: %s" % os.getcwd() |
| 37 | |
| 38 | def system(debugger, command_line, result, dict): |
| 39 | """Execute the command (a string) in a subshell.""" |
| 40 | args = shlex.split(command_line) |
| 41 | process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 42 | output, error = process.communicate() |
| 43 | retcode = process.poll() |
| 44 | if output and error: |
| 45 | print "stdout=>\n", output |
| 46 | print "stderr=>\n", error |
| 47 | elif output: |
| 48 | print output |
| 49 | elif error: |
| 50 | print error |
| 51 | print "retcode:", retcode |