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

Command Line How-To Python Quick-Tip

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 argv function.

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 sys
def 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