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