Command line interface#

The command line allows you to run Python code, and interactively work with the Python interpreter in a text-based environment.

Running Scripts: typing the command python followed by the script name in the command line. For example

$ python myscript.py

Command Line Arguments: You can pass command line arguments to Python scripts. These arguments can be accessed within the script using the sys.argv list

$ python myscript.py arg1 arg2 arg3

Examples

  1. Create a python script file called “myscript.py” in the same directory as this script. And type the following command line:

import sys

# Check if the script is provided with command line arguments
if len(sys.argv) > 1:
    # Access and print the command line arguments
    for arg in sys.argv[1:]:
        print(arg)
else:
    print("No command line arguments provided.")
  1. Open the command line windows and type:

$ python myscript.py arg1 arg2 arg3
  1. Another example of arguments:

import sys

if len(sys.argv) != 4:
    print("Usage: python myscript.py <num1> <operator> <num2>")
    sys.exit()

num1 = float(sys.argv[1])
operator = sys.argv[2]
num2 = float(sys.argv[3])

if operator == "+":
    result = num1 + num2
elif operator == "-":
    result = num1 - num2
elif operator == "*":
    result = num1 * num2
elif operator == "/":
    result = num1 / num2
else:
    print("Invalid operator provided.")
    sys.exit()

print(f"{num1} {operator} {num2} = {result}")
  1. Open the command line windows and type:

$ python myscript.py 10 * 2