Commandline arguments in Python

23 Apr 2024

In Python commandline arguments can easily be passed to a script using the sys.argv list. The sys.argv list is a sequence of strings, where the first element (sys.argv[0]) is the name of the script being executed, and the following elements contain any additional arguments passed to the script. Here's an example:
import sys

print(!The name of the script is: " + sys.argv[0])
print("The arguments passed to the script are: " + str(sys.argv[1:]))
Assuming the above script is saved as example.py, we can run it with the following command:
python3 example.py arg1 arg2 arg3
This will produce the following output:
The name of the script is: example.py
The arguments passed to the script are: ['arg1', 'arg2', 'arg3']
You can use these extra arguments to modify the behavior of your script and make them more flexible and adaptable for different use cases. For example, you could use them to specify input files, directories, URLs or to enable certain features of your program. Personally I have used them to input a URL for a Google Lighthouse script.

It's worth noting that sys.argv can be manipulated directly, so it's a good idea to validate and sanitize any arguments passed to your script to avoid unexpected behavior or any security issues.

You might also enjoy

Removing EXIF data from an image using Python

Removing EXIF data from an image using Python

Published 2024-09-18 — Updated 2024-11-21

Python

EXIF data is information that is embedded within digital images and is automatically generated by digital cameras and smartphones.

Read the post →
Privacy policy

Privacy policy

Published 2024-07-28

Privacy/data policy for the website PhilipSoerensen.com

Read the post →
Converting images

Converting images

Published 2024-05-14 — Updated 2024-07-28

Converting images to and from various different formats (AVIF, DNG, WEBP etc.) with Ubuntu CLI.

Read the post →