0
import sys

def fun( a=7, b=1 ):
    print a, b

fun()
fun( a=5 )
fun( sys.argv[1:] )

The first fun() prints out '7,1', the second prints out '5,1', but the third prints out '['a=8', 'b=6'] 1]'. I would like to be able to call my program with

python my_program.py a=5 b=6

to change the value of the printed a and b. But this doesn't work since sys.argv[1] is a list of strings.

Is there any way to convert the the string list to a form the function can understand?

2 Answers 2

4

Use ** for kwarg unpacking:

d = {}
for a in sys.argv[1:]:
    k, v = a.split('=')
    d[k] = int(v)
func(**d)

Another way, using the csv module:

import csv
func(**{k: int(v) for k, v in csv.reader(sys.argv[1:], delimiter='=')})

As @MartijnPieters noted you may use the argparse module

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-a', type=int)
parser.add_argument('-b', type=int)

args = parser.parse_args()
fun(**dict(args._get_kwargs()))

but then you have to adjust the way you input your arguments

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

3 Comments

Oh damn, 5 second difference
@Haidro See what happens next. I bet the top answer will be Martijn's anyway
This now prints out 'a=5,b=6', not '5,6'. It is essentially setting a = 'a=5', b = 'b=6'. Is there a way to get the function to treat them as keywords?
4

Use * to unpack a list into arguments:

fun(*sys.argv[1:])

Note that this will result in string arguments; sys.argv command line entries are always strings.

You may want to look into the argparse module to handle command line arguments for you, including automatic conversion:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-a', type=int, default=7)
parser.add_argument('-b', type=int, default=1)
args = parser.parse_args()

func(args.a, args.b)

Then use:

$ python my_program.py -a=5 -b=6

The added advantage here is that you get proper help feedback, and you follow standard command-line conventions:

$ python my_program.py --help
usage: [-h] [-a A] [-b B]

Process some integers.

optional arguments:
  -h, --help  show this help message and exit
  -a A
  -b B

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.