lettura simple

Passing parameters and arguments to a Python program from the command line

If you've ever dabbled in Python scripting or programming, you'll know the magic that happens when you bring parameters or arguments into play from the command line. Imagine this:

python script_name parameter1 parameter2 ...

Here's where the show begins. These players, our parameters, find themselves snugly stored in an array known as sys.argv, a part of the wider sys module.

Perhaps you're wondering about the name 'argv'? Well, it's short for 'argument vector'. Quite fitting, don't you think?

Let's dive deeper. The first argument in this list assumes the role of the first parameter, with the second stepping up as the second parameter, and so on. The structure is as neat as a pin.

For a little practical demonstration, try saving this script under the name "myScript.py"

import sys
print(sys.argv)

Now, get ready to run this script from the command line, but not before you've tagged along two parameters.

myScript.py aaa bbb

Now, watch as the script takes in the parameters ("aaa" and "bbb"), tucking them safely into the sys.argv list.

What's more, it even displays the list content for you.

['aaa', 'bbb']

What if you only wanted to peek at the first argument? No problem! Just 1 in on the index with square brackets like this:

import sys
print(sys.argv[1])

In this case, the script puts "aaa" in the spotlight.

aaa

You can pull the same trick for the second argument. Just dial 2 in the index within square brackets.

import sys
print(sys.argv[2])

The script then brings "bbb" onto the stage.

bbb

An important heads-up - these parameters are treated as strings when saved in the list.

So, if you're thinking of passing an integer to the script, remember to run it through the int() function for a smooth conversion.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin