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:

Starting With Chords

A lot of people play fiddle. Basically nobody starts by learning chords before learning melodies. But that's actually how I learned. I started with chords. One of the nice things about learning to play violin this way is that you can go busking even…

via Anna Wise's Blog Posts November 15, 2024

Stuffies

I have some stuffies and I just have a bunny. Bunny is a rabbit. Woof is a seal. My favorite stuffie is bun bun. I play with my stuffies. Sometimes I jump up with them and I roll them. I can just throw them in the air when I want to play bthululubp wi…

via Nora Wise's Blog Posts November 15, 2024

You Can Buy A Malaria Net

2024 election takes

via Thing of Things November 6, 2024

more     (via openring)