Skip to main content

Python Reference

Last tended Feb 17, 2024 Tended twice Planted Feb 6, 2024

Command-line arguments

Use argparse to configure command-line arguments:

import argparse

VERSION = "1.0.0"

parser = argparse.ArgumentParser(description='Describe your CLI')
parser.add_argument("-v", "--version", action="version", version=f"lorem {VERSION}", help="print version and exit")
parser.add_argument("count", nargs="?", default=1, type=int, help="number of sentences to generate (default: 1)")

args = parser.parse_args()
count = args.count

Read about argparse

Catching exceptions

Use try and except to catch exceptions:

try:
    # Code that might raise an exception
    if bad_condition:
        # Or throw your own
        raise Exception("Something went wrong")
except Exception as e:
    print(f"An error occurred: {e}")

Formatting strings

Use f strings:

name = "world"
print(f"Hello {name}!")

Reading a file

Use open to read a file:

with open("file.txt", "r") as file:
    contents = file.read()

Using with ensures the file is closed when the block is exited.

Writing a file

Use open to write a file:

with open("file.txt", "w") as file:
    file.write("Hello, world!")

Using with ensures the file is closed when the block is exited.

Requirements files

To generate a requirements.txt file:

pip freeze > requirements.txt

To install dependencies from a requirements.txt file:

pip install -r requirements.txt