Cli arguments

Contents

Cli arguments#

This page discusses tools in python that allow you to work with stdin paramters used when python started.

Manual#

You can access the stdIn used to run python from the sys.argv attribute. This is list of string containing all the arguments passed to the python during the call.


The following cell shows the arguments, which is used to run the jupyter kernel, which is used as the environment on this site.

import sys
sys.argv
['/home/fedor/.virtualenvs/python/lib/python3.12/site-packages/ipykernel_launcher.py',
 '--f=/run/user/1000/jupyter/runtime/kernel-v394a53a093ec8001e3f58f0d7c748849ec5233782.json']

The following cell creates in general the same example, but in a different py file.

%%writefile /tmp/python_cli_example.py
import sys
for v in sys.argv: print(v)
Writing /tmp/python_cli_example.py

So now we can run this script with any set of parameters.

!python3 /tmp/python_cli_example.py value{1..10}
/tmp/python_cli_example.py
value1
value2
value3
value4
value5
value6
value7
value8
value9
value10

Argparse#

Argparse is a library that allows you to describe parameters that should be passed to the program when called from the command line. There are few central features of ArgumentParser.add_argument method:

  • To define positional parameters of the program, use only line as first positional argument of the add_argument;

  • To define an option, add the prefix -- to the first positional argument of the add_argument;

  • You can access to the values by using ArgumentParser.parse_args().<option dest>.


In a real project, you’ll write your scripts in separate files. The following cell creates a script and writes it to disk. This script uses argparse to implement a command-line interface and prints the values of the received arguments:

%%writefile /tmp/basic_argparse.py
import argparse

my_parser = argparse.ArgumentParser(
    description='Process some integers.'
)
my_parser.add_argument(
    "positional", 
    help = "Example of the positional argument.",
)
my_parser.add_argument(
    "--option",
    help = "Option that takes value."
)

args = my_parser.parse_args()
print(
    "positional : ", args.positional, "\n",
    "option : ", args.option,
    sep = ""
)
Writing /tmp/basic_argparse.py

Here is the --help output for the created programme.

%%bash
python3 /tmp/basic_argparse.py --help
usage: basic_argparse.py [-h] [--option OPTION] positional

Process some integers.

positional arguments:
  positional       Example of the positional argument.

options:
  -h, --help       show this help message and exit
  --option OPTION  Option that takes value.

Here is example of calling programm.

%%bash
python3 /tmp/basic_argparse.py\
    positional_value\
    --option option_value
positional : positional_value
option : option_value