0

I have a python function that requires several parameters. Something like:

def func(par1=1, par2=2, par3=3):
... 

I want to make this callable from command line such as: function.py par1=1 par2=2 par3=3.

I was thinking of doing it something like this:

import sys

if sys.argv[0][0:4]=="par1":
   par1=int(sys.argv[0][5:])
else:
   par1=1

but it doesn't look very nice, as the user might pass just some parametrs, or they might pass it as par1 =1 or par1= 1 or par1 = 1 so I would have to hard code with if-else all these possibilities. Is there a nicer, more professional solution? Thank you!

2
  • function.py par1=1 par2=2 par3=3 violates expectations on UNIX commands. function.py --par1=1 --par2=2 --par3=3 looks much better. Consult argparse documentation. Commented Nov 21, 2019 at 5:35
  • 1
    Possible duplicate of What's the best way to parse command line arguments? Commented Nov 21, 2019 at 5:48

2 Answers 2

3

Use argparse from the standard library

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--par1", type=int, default=1, help="This is the description")
opts = parser.parse_args()

print(opts.part1)

checkout the docs for more details: https://docs.python.org/3/library/argparse.html

Sign up to request clarification or add additional context in comments.

Comments

0

As mentioned in Amadan's comment, you probably want function.py --par1=1 --par2=2 --par3=3 and not function.py par1=1 par2=2 par3=3

For the former, you can use

function.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--par1", default=11)
parser.add_argument("--par2", default=22)
parser.add_argument("--par3", default=33)
parser.add_argument("--par4", default=44)
opts = parser.parse_args()

print(opts.par1, opts.par2, opts.par3, opts.par4)
$ python function.py  # default values
11 22 33 44

$ python function.py --par1 99  # spaces are OK
99 22 33 44

$ python function.py --par1=99  # = are OK
99 22 33 44

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.