0 votes
1 view
in Python by (12.5k points)

I am setting up a Python script to calculate a risk score. The script will need to be run from the command line and will include all the variables needed for the calculation.

The needed format is: python test.ipynb Age 65 Gender Male

Age and Gender are the variable names, with 65 (integer years) and Male (categorical) being the variables.

I am very new to Python, so the skill level is low. - Looked for examples - Read about getopt and optoparse - Attempted to write Python code to accomplish this

import sys, getopt

def main(argv):

   ageValue = 0

   genderValue = 0


      opts, args = getopt.getopt(argv,"",["Age","Gender"])

   except getopt.GetoptError:

      print ('Error, no variable data entered')


   for opt, arg in opts:

      if opt == "Age":

         ageValue = arg

      if opt == "Gender":

         genderValue = arg

   print ('Age Value is  ', ageValue)

   print ('Gender Value is ', genderValue)

This is the output from this code -

Age Value is 0

Gender Value is 0

The expected output is

Age Value is 65

Gender Value is Male

1 Answer

0 votes
by (24.8k points)

Argparse is what I use. Here's some code.

import argparse 

parser = argparse.ArgumentParser(description='Do a risk thing')

parser.add_argument('-a', '--age', dest='age', type=int, help='client age')

parser.add_argument('-g', '--gender', dest='gender', type=str, help='client gender')

args = parser.parse_args()

print('Age: {}\nGender: {}'.format(args.age, args.gender))

Usage python test.py --age 25 --gender male.

Note that this won't work with a python notebook. For that, I'm not sure of a solution. Also, you can really configure the heck out of argparse, so I'd recommend reading the docs.

Related questions

+4 votes
5 answers
asked May 24, 2019 in Python by Aditya98 (1.3k points)
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !