• Posts
  • RSS
  • ◂◂RSS
  • Contact

  • 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:

    Be less scared of overconfidence

    deferring to markets • deferring to experts • deferring to low-information heuristics • why they fail • blindness to outliers • what to do instead

    via benkuhn.net November 30, 2022

    Corncob Dolls

    I went to a farm and at the farm I got to see a corncrib and the corn that had fell out of the corncrib that no one wanted I got to use my fingers to take off the corn kernels and once the cobs were empty I put them in a bag and then once I got back to the…

    via Anna Wise's Blog Posts November 7, 2022

    Light Switch

    When I got my loft bed it was just so annoying every morning to have to get out of bed, climb down the ladder, turn the light on, and climb back up, just so I could see stuff. I decided to make a string for my light switch because I really wanted to be abl…

    via Lily Wise's Blog Posts November 7, 2022

    more     (via openring)


  • Posts
  • RSS
  • ◂◂RSS
  • Contact