Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k 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

   try:

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

   except getopt.GetoptError:

      print ('Error, no variable data entered')

      sys.exit(2)

   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 (25.1k 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

0 votes
1 answer
0 votes
1 answer
asked Feb 15, 2021 in SQL by adhiraj (4k points)
+1 vote
1 answer
asked May 29, 2019 in R Programming by Ritik (3.5k points)
+1 vote
1 answer

Browse Categories

...