blob: 6e3462e1c8630d2eba7d7ea2fe16b14bd2e19e9a [file] [log] [blame]
Johnny Chende6ade02011-10-12 19:16:06 +00001"""Utility for changing directories and execution of commands in a subshell."""
2
Kate Stoneb9c1b512016-09-06 20:57:50 +00003import os
4import shlex
5import subprocess
Johnny Chende6ade02011-10-12 19:16:06 +00006
Johnny Chen7596f932011-10-13 01:20:34 +00007# Store the previous working directory for the 'cd -' command.
Kate Stoneb9c1b512016-09-06 20:57:50 +00008
9
Johnny Chen7596f932011-10-13 01:20:34 +000010class 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 Stoneb9c1b512016-09-06 20:57:50 +000022
Johnny Chende6ade02011-10-12 19:16:06 +000023def chdir(debugger, args, result, dict):
Johnny Chena4c6a7b2011-10-28 21:23:58 +000024 """Change the working directory, or cd to ${HOME}.
25 You can also issue 'cd -' to change to the previous working directory."""
Johnny Chen7596f932011-10-13 01:20:34 +000026 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 Chende6ade02011-10-12 19:16:06 +000039 print "Current working directory: %s" % os.getcwd()
40
Kate Stoneb9c1b512016-09-06 20:57:50 +000041
Johnny Chende6ade02011-10-12 19:16:06 +000042def system(debugger, command_line, result, dict):
43 """Execute the command (a string) in a subshell."""
44 args = shlex.split(command_line)
Kate Stoneb9c1b512016-09-06 20:57:50 +000045 process = subprocess.Popen(
46 args,
47 stdout=subprocess.PIPE,
48 stderr=subprocess.PIPE)
Johnny Chende6ade02011-10-12 19:16:06 +000049 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