summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEric Lin <anselor@gmail.com>2020-02-24 16:11:32 -0500
committerEric Lin <anselor@gmail.com>2020-02-24 17:02:00 -0500
commitec7b442eff9f6488509d43b6ae2e902fcdb79ddf (patch)
treeb7705191352f7681f5b1217331107470139fe720
parentfea1bc15f4a53aa72d16c2985377fe3987b6b348 (diff)
downloadcmd2-git-ec7b442eff9f6488509d43b6ae2e902fcdb79ddf.tar.gz
Updated python scripting exmaple to illustrate how
stdout/stderr is automatically captured in CommandResult during python scripting. Fixes #898
-rwxr-xr-xexamples/python_scripting.py28
-rw-r--r--examples/scripts/conditional.py18
2 files changed, 25 insertions, 21 deletions
diff --git a/examples/python_scripting.py b/examples/python_scripting.py
index 198e784d..62dd3091 100755
--- a/examples/python_scripting.py
+++ b/examples/python_scripting.py
@@ -29,12 +29,11 @@ class CmdLineApp(cmd2.Cmd):
super().__init__(use_ipython=True)
self._set_prompt()
self.intro = 'Happy 𝛑 Day. Note the full Unicode support: 😇 💩'
- self.self_in_py = True
def _set_prompt(self):
"""Set prompt so it displays the current working directory."""
self.cwd = os.getcwd()
- self.prompt = ansi.style('{!r} $ '.format(self.cwd), fg='cyan')
+ self.prompt = ansi.style(f'{self.cwd} $ ', fg='cyan')
def postcmd(self, stop: bool, line: str) -> bool:
"""Hook method executed just after a command dispatch is finished.
@@ -57,33 +56,31 @@ class CmdLineApp(cmd2.Cmd):
if not arglist or len(arglist) != 1:
self.perror("cd requires exactly 1 argument:")
self.do_help('cd')
- self.last_result = cmd2.CommandResult('', 'Bad arguments')
+ self.last_result = '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 = None
data = None
if not os.path.isdir(path):
- err = '{!r} is not a directory'.format(path)
+ err = f'{path} is not a directory'
elif not os.access(path, os.R_OK):
- err = 'You do not have read access to {!r}'.format(path)
+ err = f'You do not have read access to {path}'
else:
try:
os.chdir(path)
except Exception as ex:
- err = '{}'.format(ex)
+ err = f'{ex}'
else:
- out = 'Successfully changed directory to {!r}\n'.format(path)
- self.stdout.write(out)
+ self.poutput(f'Successfully changed directory to {path}')
data = path
if err:
self.perror(err)
- self.last_result = cmd2.CommandResult(out, err, data)
+ self.last_result = data
# Enable tab completion for cd command
def complete_cd(self, text, line, begidx, endidx):
@@ -100,20 +97,17 @@ class CmdLineApp(cmd2.Cmd):
if unknown:
self.perror("dir does not take any positional arguments:")
self.do_help('dir')
- self.last_result = cmd2.CommandResult('', 'Bad arguments')
+ self.last_result = '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.poutput(f'{f}')
+ self.poutput('')
- self.last_result = cmd2.CommandResult(data=contents)
+ self.last_result = contents
if __name__ == '__main__':
diff --git a/examples/scripts/conditional.py b/examples/scripts/conditional.py
index eb4c203e..eb710695 100644
--- a/examples/scripts/conditional.py
+++ b/examples/scripts/conditional.py
@@ -24,13 +24,20 @@ else:
original_dir = os.getcwd()
# Try to change to the specified directory
-app('cd {}'.format(directory))
+result = app('cd {}'.format(directory))
# Conditionally do something based on the results of the last command
-if self.last_result:
+if result:
+ print(f"STDOUT: {result.stdout}\n")
+ print(f"STDERR: {result.stderr}\n")
+
print('\nContents of directory {!r}:'.format(directory))
- app('dir -l')
- print('{}\n'.format(self.last_result.data))
+ result = app('dir -l')
+
+ print(f"STDOUT: {result.stdout}\n")
+ print(f"STDERR: {result.stderr}\n")
+
+ print('{}\n'.format(result.data))
# Change back to where we were
print('Changing back to original directory: {!r}'.format(original_dir))
@@ -38,3 +45,6 @@ if self.last_result:
else:
# cd command failed, print a warning
print('Failed to change directory to {!r}'.format(directory))
+
+ print(f"STDOUT: {result.stdout}\n")
+ print(f"STDERR: {result.stderr}\n")