Intermediate Chapter 180 · 30 min read · Module 14: Advanced Application Development
Python Scripts
- After this chapter you can explain the difference between a script and a module and use the __main__ guard.
- You can read command line arguments with sys.argv and with argparse.
- You can write a main function that returns an exit status and use sys.exit.
- You can read from standard input and write to standard output and standard error.
- You can structure a small script so that it is easy to test and reuse.
A script is a Python file that you run to get a job done. It might rename a hundred photos, clean a text file, check a list of web addresses or print a daily report. Scripts are where many people first feel the real power of Python, because a few lines can replace an hour of boring manual work.
Writing a script that works once on your own computer is easy. Writing one that other people can run, that explains how to use it, that fails with a clear message and that can also be imported by other code takes a few extra habits. These habits are the subject of this chapter.
You will learn the standard layout of a script, how to read arguments from the command line, how to talk to standard input and output, how to signal success or failure with an exit code, and how to keep your logic in functions so that you can test it.
Script or module?
Any .py file can be run directly and can also be imported by another file. The same file is called a script when you run it and a module when you import it. Python tells your code which case applies through the special variable __name__. When the file is run directly, __name__ is the text "__main__". When the file is imported, __name__ is the name of the module.
Because of this, almost every well written script uses the guard if __name__ == "__main__":. Code inside the guard runs only when the file is executed directly. Code outside it, such as function definitions, is safe to import without side effects.
def greet(name):
return f"Hello, {name}!"
def main():
print(greet("Asha"))
print(__name__)
if __name__ == "__main__":
main()Reading command line arguments
When you start a script as python tool.py report.txt 5, the extra words are passed to your program as a list of strings called sys.argv. The first item, sys.argv[0], is the script name. The rest are the arguments. Every item is text, so you must convert numbers yourself with int() or float().
Working with sys.argv directly is fine for tiny tools. For anything bigger, use the argparse module. It builds a help message, checks types, supports optional flags and prints a clear error if the user types something wrong. You create a parser, describe each argument, and call parse_args(). For testing you can pass your own list of strings to parse_args, which is what the next example does.
import argparse
parser = argparse.ArgumentParser(description="Repeat a word")
parser.add_argument("word")
parser.add_argument("-n", "--times", type=int, default=2)
parser.add_argument("--upper", action="store_true")
args = parser.parse_args(["hi", "-n", "3", "--upper"])
text = args.word.upper() if args.upper else args.word
print((text + " ") * args.times)| Idea | Tool | Example |
|---|---|---|
| Raw arguments | sys.argv | sys.argv[1] |
| Parsed arguments | argparse | parser.add_argument('--times', type=int) |
| Read input lines | sys.stdin | for line in sys.stdin: |
| Error messages | sys.stderr | print('bad', file=sys.stderr) |
| Exit status | sys.exit | sys.exit(1) |
Standard input, output and errors
Every program has three streams. Standard input (sys.stdin) is where data comes in, standard output (sys.stdout) is where normal results go, and standard error (sys.stderr) is for warnings and error messages. print() writes to standard output by default. To write to the error stream, use print(..., file=sys.stderr).
Keeping results and errors apart matters because users can redirect them. A user may save your results to a file with python tool.py > out.txt and still see the error messages on the screen. Reading from sys.stdin also lets your script work in a pipeline, where the output of one program feeds the next.
import sys
total = 0
for line in sys.stdin:
total += len(line.split())
print("words:", total)Exit codes
When a program ends it returns a small number to the operating system. Zero means success and any other number means failure. Shell scripts and other tools read this number to decide what to do next. Call sys.exit(0) for success or sys.exit(1) for a general failure. If you pass a string to sys.exit, Python prints it to standard error and exits with code 1.
A clean pattern is to let main() return the exit code and then write sys.exit(main()) inside the guard. This keeps main() easy to call from tests, because it just returns a number.
def main(values):
if not values:
print("nothing to add")
return 1
print("sum:", sum(values))
return 0
print(main([2, 3, 4]))
print(main([]))Keeping scripts easy to test
Put the real work in small functions that take arguments and return values. Let main() do only the wiring: parse arguments, call the functions and print results. A function that returns a value can be tested by simply calling it, while code that is mixed with input() and print() is harder to check. Constants such as file names belong at the top of the file, and a short docstring at the start explains what the script does.
#!/usr/bin/env python3 at the top of a script and make it executable with chmod +x. Then you can run it as ./tool.py. This is called a shebang line.python tool.py data.txt --times 3
echo $?Python syntax
if __name__ == "__main__":
main()import sys
print(sys.argv[1:])import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()import sys
sys.exit(main())Real-world applications
- Renaming or sorting many files in a folder.
- Cleaning and converting data files such as CSV or text logs.
- Daily or weekly reports run by a scheduler.
- Small command line tools shared with a team.
- Glue code that connects other programs in a pipeline.
Common mistakes
Fix: Wrap the entry point in main() and call it under if __name__ == "__main__".
Fix: Convert with int() or float(), or let argparse do it with type=int.
Fix: Write errors with print(..., file=sys.stderr) and exit with a non zero code.
Fix: Use argparse, or check len(sys.argv) first and show a usage message.
Important tips
- Write a short docstring that says what the script does and how to run it.
- Prefer argparse once a script has more than one argument.
- Keep functions small and free of input() so they are easy to test.
- Use pathlib for file paths so the script works on every operating system.
- Return exit codes from main() instead of calling sys.exit deep inside functions.
Key points summary
- A file is a script when run and a module when imported.
- __name__ equals "__main__" only when the file is run directly.
- sys.argv is a list of text; argparse parses it for you.
- stdout is for results, stderr is for errors.
- Exit code 0 means success, non zero means failure.
Exam and interview points
- Know that __name__ is "__main__" when a file runs directly.
- sys.argv[0] is the script name, user arguments start at index 1.
- Exit status 0 means success.
- argparse generates --help automatically.
- print goes to stdout by default; sys.stderr is for diagnostics.
Quick revision
- Script = run, module = imported.
- Use the __main__ guard.
- sys.argv holds text arguments.
- argparse = options, types and help.
- sys.exit(0) success, non zero failure.
- Errors go to sys.stderr.
Frequently asked questions
Why do I need if __name__ == "__main__"?
It stops your script from running its main work when another file imports it. This lets you reuse functions and test them safely.
What is the difference between sys.argv and argparse?
sys.argv is a plain list of strings. argparse reads that list, converts types, adds options and help, and prints friendly errors.
How do I run a script?
Open a terminal in its folder and type python script.py followed by any arguments. On some systems the command is python3.
Can a script return a value?
A script returns an exit code to the operating system, which is a small integer. Use sys.exit(code) to set it. For data, print it or write a file.
How do I make a script read from a pipe?
Read from sys.stdin, for example with for line in sys.stdin. The shell then connects the previous program's output to it.
Practise this chapter
20 practice questions Take the chapter quiz