Add a filename in the command line when running a Python script

flaviabastos

Flávia Bastos

Posted on March 22, 2019

Add a filename in the command line when running a Python script

OR: Run a Python script with arguments

You can add arguments to the command line when running python scripts by importing the sys module from Python’s standard library and using its argvfunction.

Some examples:

A simple script that displays the user name:

def main(): name = 'Frodo' print(f'Hello, {name}')if \_\_name\_\_ == "\_\_main\_\_": main()

Ran as python3 my_script.py, will display:

Hello, Frodo

This can be refactored to display whatever name is used as arguments in the command line when calling the script:

import sysdef main(): name = sys.argv[1] print(f'Hello, {name}')if \_\_name\_\_ == "\_\_main\_\_": main()

Add the name you would like to use to the command line:

python3 my\_script.py Galadriel

will now output:

Hello, Galadriel

You will notice that in the script we’re assigning the element at index 1 from argv to name. If you add this line to the script:

print(f'ARGS: {sys.argv}')

you will notice that argv returns a list with all the arguments passed to the Python script and the first argument is always the script’s name:

ARGS: ['my\_script.py', 'Galadriel']

This can be really useful if you need to write a script that will read a file, for example. In that case, you don’t need to hard code the file name inside the script but pass it when running the script:

python3 my\_script.py my\_file.txt

The post _Add a filename in the command line when running a Python script was originally published at _flaviabastos.ca

💖 💪 🙅 🚩
flaviabastos
Flávia Bastos

Posted on March 22, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related