def do_cd(self, arglist): """Change directory. Usage: cd <new_dir> """ # Expect 1 argument, the directory to change to if not arglist or len(arglist) != 1: self.perror("cd requires exactly 1 argument:", traceback_war=False) self.do_help('cd') self._last_result = cmd2.CmdResult('', 'Bad arguments') return # Convert relative paths to absolute paths path = os.path.abspath(os.path.expanduser(arglist[0])) # Make sure the directory exists, is a directory, and we have read access out = '' err = '' if not os.path.isdir(path): err = '{!r} is not a directory'.format(path) elif not os.access(path, os.R_OK): err = 'You do not have read access to {!r}'.format(path) else: try: os.chdir(path) except Exception as ex: err = '{}'.format(ex) else: out = 'Successfully changed directory to {!r}\n'.format(path) self.stdout.write(out) if err: self.perror(err, traceback_war=False) self._last_result = cmd2.CmdResult(out, err)
def test_cmdresult(cmdresult_app): arg = 'foo' run_cmd(cmdresult_app, 'affirmative {}'.format(arg)) assert cmdresult_app._last_result assert cmdresult_app._last_result == cmd2.CmdResult(arg) arg = 'bar' run_cmd(cmdresult_app, 'negative {}'.format(arg)) assert not cmdresult_app._last_result assert cmdresult_app._last_result == cmd2.CmdResult('', arg)
def do_dir(self, args, unknown): """List contents of current directory.""" # No arguments for this command if unknown: self.perror("dir does not take any positional arguments:", traceback_war=False) self.do_help('dir') self._last_result = cmd2.CmdResult('', 'Bad arguments') return # Get the contents as a list contents = os.listdir(self.cwd) fmt = '{} ' if args.long: fmt = '{}\n' for f in contents: self.stdout.write(fmt.format(f)) self.stdout.write('\n') self._last_result = cmd2.CmdResult(contents)
def do_negative(self, arg): self._last_result = cmd2.CmdResult('', arg)
def do_affirmative(self, arg): self._last_result = cmd2.CmdResult(arg)