Monday 10/30¶
Reminders¶
- PA1 Part B is due 10/31
- Quiz this week is on while loops and modules.
Thonny Debugger Settings¶
- Run & Debug → Preferred debugger: faster
- This is the debugging style of most IDEs.
- Disables expression/block-level stepping.
Code Example¶
coin_toss.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
The Command Line¶
- Why?
- Computing work often involves accessing machines remotely.
- Supports automation: renaming one file is easy using a GUI file manager. Renaming 10,000 files will probably be easier using a command-line tool.
- 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
Running Python Code in the Terminal¶
From the command line, use the python3
command to run a program.
$ python3
coin_toss.py
Or from Thonny, press ^Ctrl+T to "Run current script in terminal."
Command-line 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.
coin_toss_file.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
-
You can also run programs via Thonny's shell using the %Run command:
>>> %Run coin_toss_file.py tosses.txt 100
This command is equivalent to
python3 coin_toss_file.py tosses.txt 100
.
Walking the File System¶
- Demo of the
os
module and thesy
s module -
Step through this program using the debugger
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
"""Find all Python files in a given directory.""" import os import sys def main(path): # for each directory starting from path for root, dirs, files in os.walk(path): print() print(f"{root = }") print(f"{dirs = }") print(f"{files = }") print() # for each Python file in current directory for filename in sorted(files): if filename.endswith(".py"): filepath = os.path.join(root, filename) print(filepath) if __name__ == "__main__": if len(sys.argv) == 1: # no arguments; use current directory main(".") else: # use the "first" command-line argument main(sys.argv[1])
-
Modify this program so that it takes a second command-line argument that is the name of a particular file to search for. Print the full path to the file if it is found. Keep in mind that there could be multiple files with the same name. For example:
$ python3 search.py /home/spragunr names.txt /home/spragunr/Downloads/149_POGIL/Act11/src/names.txt /home/spragun/courses/CS159/docs/grading/S18/PA5-code/names.txt