Lazy Python Argument Parsing

November 2nd, 2022
python, tech
When I'm writing real Python programs I use argparse. When I'm writing quick scripts, I destructure sys.argv[1:]. For example:

width, depth, height = sys.argv[1:]
...

Or, if I need to import the file:

def start(width, depth, height):
  ...

if __name__ == '__main__':
  start(*sys.argv[1:])

This is a very simple way of handling positional arguments. It ignores sys.argv[0] which is likely the name of the script, and then assigns the remaining arguments to the variables. If I provide the wrong number of arguments it's a bit shouty, but it's clear enough for a quick script and does remind me of the intended arguments:

Traceback (most recent call last):
  File "example.py", line 2, in 
    width, depth, height = sys.argv[1:]
ValueError: too many values to unpack (expected 3)

Comment via: facebook, lesswrong

Recent posts on blogs I like:

Jealousy In Polyamory Isn't A Big Problem And I'm Tired Of Being Gaslit By Big Self-Help

The nuance is in the post, guys

via Thing of Things July 18, 2024

Trust as a bottleneck to growing teams quickly

non-trust is reasonable • trust lets collaboration scale • symptoms of trust deficit • how to proactively build trust

via benkuhn.net July 13, 2024

Coaching kids as they learn to climb

Helping kids learn to climb things that are at the edge of their ability The post Coaching kids as they learn to climb appeared first on Otherwise.

via Otherwise July 10, 2024

more     (via openring)