MCPcopy Index your code
hub / github.com/python-cmd2/cmd2 / do_cd

Method do_cd

examples/python_scripting.py:59–92  ·  view source on GitHub ↗

Change directory. Usage: cd .

(self, arglist: list[str])

Source from the content-addressed store, hash-verified

57
58 @cmd2.with_argument_list
59 def do_cd(self, arglist: list[str]) -> None:
60 """Change directory.
61 Usage:
62 cd <new_dir>.
63 """
64 # Expect 1 argument, the directory to change to
65 if not arglist or len(arglist) != 1:
66 self.perror("cd requires exactly 1 argument:")
67 self.do_help("cd")
68 self.last_result = "Bad arguments"
69 return
70
71 # Convert relative paths to absolute paths
72 path = os.path.abspath(os.path.expanduser(arglist[0]))
73
74 # Make sure the directory exists, is a directory, and we have read access
75 err = None
76 data = None
77 if not os.path.isdir(path):
78 err = f"{path} is not a directory"
79 elif not os.access(path, os.R_OK):
80 err = f"You do not have read access to {path}"
81 else:
82 try:
83 os.chdir(path)
84 except Exception as ex: # noqa: BLE001
85 err = f"{ex}"
86 else:
87 self.poutput(f"Successfully changed directory to {path}")
88 data = path
89
90 if err:
91 self.perror(err)
92 self.last_result = data
93
94 # Enable tab completion for cd command
95 def complete_cd(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:

Callers

nothing calls this directly

Calls 3

perrorMethod · 0.80
do_helpMethod · 0.80
poutputMethod · 0.80

Tested by

no test coverage detected