1 """Utility for changing directories and execution of commands in a subshell.""" 2 3 import os, shlex, subprocess 4 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 18 def chdir(debugger, args, result, dict): 19 """Change the working directory, or cd to ${HOME}. 20 You can also issue 'cd -' to change to the previous working directory.""" 21 new_dir = args.strip() 22 if not new_dir: 23 new_dir = os.path.expanduser('~') 24 elif new_dir == '-': 25 if not Holder.prev_dir(): 26 # Bad directory, not changing. 27 print "bad directory, not changing" 28 return 29 else: 30 new_dir = Holder.prev_dir() 31 32 Holder.swap(os.getcwd()) 33 os.chdir(new_dir) 34 print "Current working directory: %s" % os.getcwd() 35 36 def system(debugger, command_line, result, dict): 37 """Execute the command (a string) in a subshell.""" 38 args = shlex.split(command_line) 39 process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 40 output, error = process.communicate() 41 retcode = process.poll() 42 if output and error: 43 print "stdout=>\n", output 44 print "stderr=>\n", error 45 elif output: 46 print output 47 elif error: 48 print error 49 print "retcode:", retcode 50