Practice: Python Scripts
Q1. Main guard message
Write a program with a function main() that prints Script running, and call it only when the file is run directly.
Goal: Use the main guard.
Q2. Add two arguments
Given the list args = ["4", "6"] (like sys.argv[1:]), convert both to int and print their sum.
Goal: Convert argument strings to numbers.
Q3. Parse a name option
Using argparse, create a parser with an option --name (default World). Parse the list ["--name", "Ravi"] and print Hello, Ravi!
Goal: Use argparse options.
Q4. Flag with store_true
Using argparse, add a flag --loud. Parse ["--loud"] and print HELLO if the flag is set, otherwise hello.
Goal: Use boolean flags.
Q5. Return an exit status
Write main(numbers) that returns 0 and prints the largest number if the list is not empty, otherwise prints empty and returns 1. Call it with [3, 9, 4] and print the returned status.
Goal: Return exit codes from main.
Q6. Count lines from stdin text
Use io.StringIO to simulate standard input containing three lines (a, b, c). Print how many lines you read.
Goal: Read input line by line.
Q7. Print to the error stream
Write code that prints OK to standard output and WARNING to standard error. Only the standard output text appears in the expected output.
Goal: Separate stdout and stderr.
Q8. What does __name__ hold?
What does this program print when it is run directly?
print(__name__)Goal: Know the value of __name__.
Q9. Slice of argv
What does this print?
argv = ["tool.py", "a", "b", "c"]
print(argv[1:])Goal: Understand sys.argv layout.
Q10. Types from argv
What does this print?
args = ["2", "3"]
print(args[0] + args[1])Goal: Remember arguments are text.
Q11. Guard blocks code
What does this print when run directly?
def hello():
print("hello")
if __name__ == "__main__":
print("main")
else:
hello()Goal: Trace the main guard.
Q12. argparse default
What does this print?
import argparse
p = argparse.ArgumentParser()
p.add_argument("--n", type=int, default=5)
args = p.parse_args([])
print(args.n * 2)Goal: Use argparse defaults.
Q13. Positional and option
What does this print?
import argparse
p = argparse.ArgumentParser()
p.add_argument("word")
p.add_argument("-n", type=int, default=1)
a = p.parse_args(["ab", "-n", "3"])
print(a.word * a.n)Goal: Combine positional and optional arguments.
Q14. Exit code from main
What does this print?
def main():
data = []
if not data:
return 2
return 0
status = main()
print("failed" if status else "ok")Goal: Interpret exit statuses.
Q15. Fix the missing guard
This script is meant to run main() only when started directly, but it also runs when imported. Fix it.
def main():
print("work")
main()Goal: Fix a missing main guard.
Q16. Fix the argument type
The script should print the double of the first argument 4, but it prints 44. Fix it.
args = ["4"]
print(args[0] * 2)Goal: Convert argument types.
Q17. Fix the error message stream
The error message below is written to standard output. Change it so that it goes to standard error and only OK remains on standard output.
import sys
print("OK")
print("error: missing file")Goal: Send errors to stderr.
Q18. Why not parse sys.argv by hand?
Give two reasons why argparse is better than reading sys.argv directly for larger scripts.
Goal: Compare sys.argv and argparse.
Q19. Meaning of exit code zero
What does an exit code of 0 mean and why do other tools care?
Goal: Understand exit statuses.
Q20. Design a cleanup script
You must write a script that removes blank lines from a text file given on the command line. Describe the main parts of the script.
Goal: Design a small script.