Read command-line arguments

Easysys Module Programs · 1 of 20

Write a Python program that prints its command-line arguments.

Advertisement
Output
show_args.py ['login', '--browser', 'firefox']

Approach

  1. Write a helper script and run it with arguments via subprocess.

Solution

Python
import subprocessimport sys with open("show_args.py", "w") as f:    f.write("import sys\nprint(sys.argv[0], sys.argv[1:])\n")print(subprocess.run([sys.executable, "show_args.py", "login", "--browser", "firefox"],                     capture_output=True, text=True).stdout.strip())
Output
show_args.py ['login', '--browser', 'firefox']

Line by line

Line 5

sys.argv[0] is the script name; the rest are the arguments, as strings.

Learn the concept

New to this topic? Read the lesson, then come back.

More sys module programs

← All 20 sys Module Programs

Leave a Comment