简体   繁体   中英

Passing multiple variables to Python script via command line

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

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.

import argparse 

if __name__ == "__main__"
   parser.add_argument('-age', required=True)
   parser.add_argument('-gender', required=True)
   args = vars(parser.parse_args())
   print(args['age'], args['gender'])


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM