diff options
Diffstat (limited to 'examples/script_conditional.py')
-rw-r--r-- | examples/script_conditional.py | 35 |
1 files changed, 22 insertions, 13 deletions
diff --git a/examples/script_conditional.py b/examples/script_conditional.py index f0ded920..c26bd5fe 100644 --- a/examples/script_conditional.py +++ b/examples/script_conditional.py @@ -4,27 +4,36 @@ This is a Python script intended to be used with the "python_scripting.py" cmd2 To run it you should do the following: ./python_scripting.py - py run('script_conditional.py') + pyscript script_conditional.py directory_path Note: The "cmd" function is defined within the cmd2 embedded Python environment and in there "self" is your cmd2 application instance. """ +import os +import sys -# Try to change to a non-existent directory -cmd('cd foobar') + +if len(sys.argv) > 1: + directory = sys.argv[1] + print('Using specified directory: {!r}'.format(directory)) +else: + directory = 'foobar' + print('Using default directory: {!r}'.format(directory)) + +# Keep track of where we stared +original_dir = os.getcwd() + +# Try to change to the specified directory +cmd('cd {}'.format(directory)) # Conditionally do something based on the results of the last command if self._last_result: - print('Contents of foobar directory:') - cmd('dir') + print('\nContents of directory {!r}:'.format(directory)) + cmd('dir -l') # Change back to where we were - cmd('cd ..') + print('Changing back to original directory: {!r}'.format(original_dir)) + cmd('cd {}'.format(original_dir)) else: - # Change to parent directory - cmd('cd ..') - print('Contents of parent directory:') - cmd('dir') - - # Change back to where we were - cmd('cd examples') + # cd command failed, print a warning + print('Failed to change directory to {!r}'.format(directory)) |