Python Practice › OS Module Programs › Program 24
Read command-line arguments
Write a Python program that reads arguments passed on the command line.
Output
arguments: ['chrome', '--headless']
Approach
- Start a child Python with arguments and read them from
sys.argv.
Solution
import subprocessimport sys with open("args_demo.py", "w") as f: f.write("import sys\nprint('arguments:', sys.argv[1:])\n")out = subprocess.run([sys.executable, "args_demo.py", "chrome", "--headless"], capture_output=True, text=True)print(out.stdout.strip())Output
arguments: ['chrome', '--headless']
Line by line
Lines 4-5
Writes a tiny script that prints its arguments.
Line 6
Runs it the way you would type python args_demo.py chrome --headless.
Learn the concept
New to this topic? Read the lesson, then come back.