Read command-line arguments

EasyOS Module Programs · 24 of 49

Write a Python program that reads arguments passed on the command line.

Advertisement
Output
arguments: ['chrome', '--headless']

Approach

  1. Start a child Python with arguments and read them from sys.argv.

Solution

Python
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.

More os module programs

← All 49 OS Module Programs

Leave a Comment