How to get the command line parameters in Python 3

/ #Python


Sometimes when you run a script on your computer, you want to make it more dynamic by accepting parameters from the command line.

A simple example

Create a new file and add this code to it:

import sys
print(sys.argv)

We import the "sys" module from Python because this is used to read information from the system. On the next line, we print a part of sys called "argv". argv stands for argument values and is a list of all the arguments and information you write in the command line.

If you run the script in your command line, you should see something like this: ['filename.py']

"filename.py" will be replaced with whatever the name you gave the file. sys.argv will always contain at least one value, and that is the name of the file. If you go go your command line and run something like this:

python filename argument

Then you will get this result: ['filename.py', 'argument']

This makes it really easy and predictable to read the values.

A better example

import sys
if len(sys.argv) == 2:
  print( "Hello %s!" % sys.argv[1] )

This little script will take the first argument after the filename and add it to the greeting. Try saving this and run it like this:

python filename.py stein

The result will be: Hello Stein!

On the second line of this script, we count the number of arguments to make sure that there are more than just the filename. On the third line, we use a string formatter to print "Hello" and add the argument in the list at position 1. If you change sys.argv[1] to sys.argv[0], the greeting will say "Hello filename.py!" instead.

As you can see, reading these arguments is really easy. Since sys.argv is just a regular Python list, there is no problem iterating over it using a for loop either.

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.