Skip to content

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

heads = 0
tails = 0
times = 1000000

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

heads = round(heads / times * 100, 2)
tails = round(tails / times * 100, 2)

print(f"Head: {heads}%, Tail: {tails}%")

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
  • Important symbols
    • ~ (tilde) means home directory
    • . (dot) means current directory
    • .. (dot dot) means parent directory
      • Notice ../wk07/coin_toss.py above

Running Python within a 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."

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

def main():
    for i, arg in enumerate(sys.argv):
        print(f"argv[{i}] == '{arg}'")

if __name__ == "__main__":
    main()

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
This command is equivalent to python3 print_args.py JMU Dukes.

Other commands can be run using an ! (Ex: !flake8 or !pytest).

Walking the File System

  • Demo of the os module and the sys module
  • Step through this program using the debugger

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
"""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])