blob: 0a29420a4eef6c9626d5ec128dae35c97e4da05e [file] [log] [blame]
Johnny Chende6ade02011-10-12 19:16:06 +00001"""Utility for changing directories and execution of commands in a subshell."""
2
3import os, shlex, subprocess
4
Johnny Chen7596f932011-10-13 01:20:34 +00005# Store the previous working directory for the 'cd -' command.
6class 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 Chende6ade02011-10-12 19:16:06 +000018def chdir(debugger, args, result, dict):
Johnny Chen7596f932011-10-13 01:20:34 +000019 """
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 Chende6ade02011-10-12 19:16:06 +000036 print "Current working directory: %s" % os.getcwd()
37
38def 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