Search⌘ K
AI Features

Command-line Arguments

Explore how to use command-line arguments in Python scripts with sys.argv and the getopt module. Learn to parse options and arguments to create flexible programs like file copy utilities with source and target filenames, and how to handle help options and program termination.

Arguments passed to a Python script are available in sys.argv.

Python 3.8
# main.py
import sys
print('Number of arguments received = ', len(sys.argv))
print('Arguments received = ', str(sys.argv))

If we want to write a program for copying the contents of one file to another, we can receive source and target filenames through command-line arguments.

Copying one file's contents to another using command-line arguments

Parsing the command line

When using the ...