Python Command Line Arguments with sys.argv

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-command-line-arguments-with-sys-argv/
PINTEREST
PINTEREST
INSTAGRAM

Python scripts can be run different ways. Python interpreter can be used to file python scripts but it is not so practical. Also scripts are not saved. After interpreter is closed or written code will be lost. Most popular usage to write and run python scripts is creating python script file and running it.

Passing parameters or options to the script is very useful. There is two popular way to pass command line arguments to the python.

  1. Getopt Module
  2. Argparse Module

We will look in details to these modules below.

Getopt Module

Getopt module is a python module which can be loaded with import sys . This module provides  command line arguments as array.

Getopt Module

Getopt Module

Save this script to the file pythoncommandlineargument.py

Make python script file executable

And we can run python script by providing arguments.

Getopt Module

Getopt Module

As we see sys.argv provides arguments as list. First element of list is the script name and others are arguments provided. We can easily get whatever we want just providing the index of the list like below.

Argument Length

We can get provided argument list length like below.

And we run our script again with arguments

Argument Length

Argument Length

ArgParser

ArgParser is used to show argument menu and parse provided argument according to menu. This module is used to create more user friendly menus.

LEARN MORE  Linux Virt-Customize Tutorial

  • Description can be provided with description=’This is a example’
  • Arguments are added with add_argument where -i is short –input is long specifier
  • Help about specified argument is provided with help=’Set Input’
ArgParser

ArgParser

We run our script by providing -h to get help menu.

ArgParser

ArgParser

Get Provided Argument

We can get provided argument by getting input from parser.

Get Provided Argument

Get Provided Argument

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/python-command-line-arguments-with-sys-argv/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)