]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - examples/customization/pwd-cd-and-system/utils.py
Vendor import of lldb trunk r290819:
[FreeBSD/FreeBSD.git] / examples / customization / pwd-cd-and-system / utils.py
1 """Utility for changing directories and execution of commands in a subshell."""
2
3 import os
4 import shlex
5 import subprocess
6
7 # Store the previous working directory for the 'cd -' command.
8
9
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
22
23 def chdir(debugger, args, result, dict):
24     """Change the working directory, or cd to ${HOME}.
25     You can also issue 'cd -' to change to the previous working directory."""
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)
39     print "Current working directory: %s" % os.getcwd()
40
41
42 def system(debugger, command_line, result, dict):
43     """Execute the command (a string) in a subshell."""
44     args = shlex.split(command_line)
45     process = subprocess.Popen(
46         args,
47         stdout=subprocess.PIPE,
48         stderr=subprocess.PIPE)
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