Reputation: 191
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
Upvotes: 0
Views: 1902
Reputation:
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'])
Upvotes: 2
Reputation: 81
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.
Upvotes: 2