Skip to content

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
import random


def flip_coin(times):
    heads = 0
    tails = 0

    for _ in range(times):
        if random.random() < 0.5:
            heads += 1
        else:
            tails += 1

    return heads, tails


if __name__ == "__main__":
    times = 100000
    heads, tails = flip_coin(times)
    heads = round(heads / times * 100, 2)
    tails = round(tails / times * 100, 2)
    print(f"Head: {heads}%, Tail: {tails}%")

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

  • 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
import random
import sys


def save_flips(file_name, times):

    with open(file_name, "w") as f:

        for _ in range(times):
            if random.random() < 0.5:
                f.write("Heads\n")
            else:
                f.write("Tails\n")


if __name__ == "__main__":
    print(f"Command Line Arguments: {sys.argv}")

    if len(sys.argv) != 3:
        print("Usage: coin_toss_file.py FILE_NAME NUM_FLIPS")
    else:
        save_flips(sys.argv[1], int(sys.argv[2]))
  • 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 the sys 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