liveBook · Manning

--outfile

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A command-line option that specifies the file to which program output should be written.

--outfile is an optional command-line argument that sends generated text to a named file instead of standard output. Its short alias is -o. section 5.5.1 section 5.3

Choose an output-handling pattern based on how much work argparse should perform:

  • Store a filename string with type=str and default='' when the program will decide how to open or write the destination. section 5.5.1
  • Use type=argparse.FileType('wt') with default=sys.stdout to receive an open writable text handle for either a file or STDOUT. section 13.1 section 13.3
  • Write to STDOUT when the option is absent; supply the filename after -o or --outfile when redirecting output. section 5.3

Redirecting Howler output

Running ./howler.py -o out.txt ../inputs/fox.txt produces no terminal output. Reading out.txt afterward shows the uppercased sentence: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.

A reusable output destination

A generated song can default to STDOUT or accept -o song.txt. With type=argparse.FileType('wt') and default=sys.stdout, later code can write to the same output handle in either case. section 13.1 section 13.1.5

Figure 5.5 A string diagram showing that our howler.py program will accept strings or files as inputs and possibly an output filename.

Shows the command-line shape: a string or file input followed by an optional output filename. section 5.3

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines aliases, defaults, string filenames, writable argparse handles, and observable command behavior.
Examples
Demonstrates Howler text-file output and Twelve Days song generation with optional filenames.
What it assumes
Assumes basic argparse usage and Python output handling while reinforcing STDOUT and writable-file selection.
What you can do after
Operate/configure Python CLI programs to write output through either a supplied file or STDOUT.
How it connects
Connects command-line arguments, argparse, file handles, sys.stdout, and standard output.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.