Python Practice › sys Module Programs › Program 1
Read command-line arguments
Write a Python program that prints its command-line arguments.
Output
show_args.py ['login', '--browser', 'firefox']
Approach
- Write a helper script and run it with arguments via subprocess.
Solution
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.