Oct 30: Command Line Scripts
Learning Objectives
After today's class, you should be able to:
- Name and describe three commands used in the terminal.
- Explain
sys.argv
and what command-line arguments are. - Summarize what you can do with the
os
andsys
modules.
Reminders¶
Thonny Expert Mode¶
In Thonny, go to Tools → Options…
- General tab → UI mode: expert
- Double click an editor tab to maximize.
- Press Esc to unmaximize the editor.
- Run & Debug → Preferred debugger: faster
- This is the debugging style of most IDEs.
- Disables expression/block-level stepping.
Example 0: Coin Toss (from Oct 6th)
../wk07/coin_toss.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
The Command Line¶
In Thonny, go to Tools → Open system shell…
- Also known as the "command line" or "terminal"
- Take 10–15 minutes to learn a few commands
- Tutorial by Django Girls (for beginners)
- Tutorial by Real Python (more advanced)
- Important symbols
~
(tilde) means home directory.
(dot) means current directory..
(dot dot) means parent directory- Notice
../wk07/coin_toss.py
above
- Notice
Running Python within a Terminal
From the command line, use the python3
command to run a program.
$ python3 coin_toss.py
Program Arguments¶
- Optional arguments can be given to a program on the command line.
sys.argv
is the list of command-line arguments passed to program.- From the View menu in Thonny, turn on the "Program arguments" box.
Example 1: Printing Arguments
print_args.py | |
---|---|
1 2 3 4 5 6 7 8 |
|
Running Python from Thonny's Shell
You can also run programs via Thonny's shell using the %Run
command:
>>> %Run print_args.py JMU Dukes
python3 print_args.py JMU Dukes
.
Other commands can be run using an !
(Ex: !flake8
or !pytest
).
Walking the File System¶
Example 2: Finding Python Files
search.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|