Debian Codegraph @

examples/scripts/conditional.py

raw symbols SCIP
1 """This is a Python script intended to be used with the "python_scripting.py" cmd2 example application.
2
3 To run it you should do the following:
4 ./python_scripting.py
5 run_pyscript scripts/conditional.py directory_path
6
7 Note: The "app" function is defined within the cmd2 embedded Python environment and in there "self" is your cmd2
8 application instance. Note: self only exists in this environment if self_in_py is True.
9 """
10
11 import os
12 import sys
13
14 if len(sys.argv) > 1:
15 directory = sys.argv[1]
16 print(f"Using specified directory: {directory!r}")
17 else:
18 directory = "foobar"
19 print(f"Using default directory: {directory!r}")
20
21 # Keep track of where we stared
22 original_dir = os.getcwd()
23
24 # Try to change to the specified directory
25 result = app(f"cd {directory}")
26
27 # Conditionally do something based on the results of the last command
28 if result:
29 print(f"STDOUT: {result.stdout}\n")
30 print(f"STDERR: {result.stderr}\n")
31
32 print(f"\nContents of directory {directory!r}:")
33 result = app("dir -l")
34
35 print(f"STDOUT: {result.stdout}\n")
36 print(f"STDERR: {result.stderr}\n")
37
38 print(f"{result.data}\n")
39
40 # Change back to where we were
41 print(f"Changing back to original directory: {original_dir!r}")
42 app(f"cd {original_dir}")
43 else:
44 # cd command failed, print a warning
45 print(f"Failed to change directory to {directory!r}")
46
47 print(f"STDOUT: {result.stdout}\n")
48 print(f"STDERR: {result.stderr}\n")