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 →
Quick and easy image recognition with 9 lines of code in Python

Quick and easy image recognition with 9 lines of code in Python

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

Machine Learning

Python

Need a quick and easy image recognition solution in Python? Learn how to create one in 9 lines of code.

Read the post →
How to easily web scrape any website with Python

How to easily web scrape any website with Python

Published 2024-05-03

Datahoarding

Notes

Python

Web development

Learn how to easily web scrape any website using Python. I go through the various techniques I use.

Read the post →