0

Currently I am using argparse for parsing arguments in this fashion :

outputFile = ""
input

def getArguments():
    parser = argparse.ArgumentParser(description='Execute the given pig script and pipe the output to given  outFile.')
    parser.add_argument('-o','--outputFile', help='Output file where pig file execution output is stored.', required=True)
    input = parser.parse_args()
    print ("========================================")
    print ("Argument to the script")
    print ("outputFile = %s" % input.outputFile )
    return input
input = getArguments()
outputFile = input.outputFile
print ("outputFile = %s" % outputFile )

My question is, is there a way a better AND/OR more compact way of writing parsing in this way ?

Note : I am especially trying to look for binding of parsed argument to the variable in the file. I hope to not to use "input" variable every-time I access input-argument nor do I want to have explicit variable declared just to copy the parameters from the argument-string to a variable.

4

1 回答 1

0

As @MartijinPieters points out in the comments, there is nothing wrong with options.arg1. Firstly, I want to echo this. There isn't a very clean (or clear IMHO) way of doing what you are asking for.


What you'll need to do is convert the options object into a dictionary. This can be done using vars:

opt_dict = vars(parser.parse_args())

Then you'll have to load all the values in the dictionary into the locals. I found this question that shows examples of how to do this. I like Ken's answer for its clarity:

for item in opt_dict.iteritems():
    eval('{0} = {1}'.format(*item))

But it allows for the possibility of dangerous input sneaking in. Also, this will have to be done outside of the getArguments() function.

However, I agree that the accepted answer on the previously linked question is probably the best way of doing this, which is to use the opt_dict to update globals.

NOTE: If you are doing this for a Pig python wrapper, like I suspect, then loading the the variables into the locals will actually be counter productive. The variables need to be passed into bind as a dictionary.

于 2013-09-20T22:14:21.640 回答