AppDividend
Latest Code Tutorials

Python Sys.argv Tutorial | Command Line Arguments Example

0

Python Sys.argv Tutorial | Command Line Arguments Example is today’s topic. In the command line, we can start the program with the additional arguments. These arguments are passed into the program

The Python sys module provides access to any command-line arguments using the sys.argv method. It serves the two purposes.

If you want to learn more about Python then check out this course Learn Python Programming Masterclass
  1. The sys.argv is the list of all the command-line arguments.
  2. len(sys.argv) is the total number of length of command-line arguments.

Here sys.argv[0] is the program, i.e. script name. If you are going to work with command line arguments, you probably want to use sys.argv. 

Python Sys.argv Tutorial

Let’s take the example of sys.argv command and see the output of the following program.

# app.py

import sys

print('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

Now, go to your command line tool and type the following command with the arguments following by space and hit the enter and see the output.

 

Python Sys.argv Tutorial

Now, analyze the output. We have passed the six arguments, and we got six arguments in the Argument List.

As mentioned above, our first argument is always the script name, and it is also being counted in the number of arguments. So even if you do not pass any arguments to your script, the argv variable always contains at least one element, and that is the script name.

The arguments in an argv method are always parsed as the String

So, you need to be careful, if you are expecting your input to be of any other type. 

You may need to cast or convert the elements according to your requirements.

Storing command line arguments

You can store any number of arguments given at the start of the program in the variables. Let’s see the following example.

# app.py

import sys

print('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

data = sys.argv[2]
print('The argument three is:', data)

Now, run the file in the command line and see the output.

 

Storing command line arguments

Finally, Python Sys.argv Tutorial | Command Line Arguments Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.