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:

Contra Scott Alexander On Apologies

I really need a short word for "complicatedly in favor of"

via Thing of Things September 12, 2024

Don't Help Kids With Contra Dancing If They Don't Need Help

If you're a kid like me, most kids have probably never heard of contra dancing before. You're probably wondering: contra dance -- what's that? Contra dancing is in some ways similar to square dancing. It's a group dance with a caller and…

via Lily Wise's Blog Posts September 9, 2024

Two 19th-century missionary memoirs in China

Life for an American family in 1860s China The post Two 19th-century missionary memoirs in China appeared first on Otherwise.

via Otherwise August 24, 2024

more     (via openring)