Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中解析和存储参数?_Python_Python 3.x - Fatal编程技术网

如何在python中解析和存储参数?

如何在python中解析和存储参数?,python,python-3.x,Python,Python 3.x,目前,我使用argparse以这种方式解析参数: 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

目前,我使用argparse以这种方式解析参数:

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 )
我的问题是,有没有一种更好和/或更紧凑的方法可以用这种方式编写语法分析


注意:我特别尝试寻找解析参数与文件中变量的绑定。我希望每次访问输入参数时不要使用“input”变量,也不希望声明显式变量只是为了将参数从参数字符串复制到变量。

正如@MartiInputers在注释中指出的那样,
选项。arg1
没有错。首先,我想回应这一点。没有一个非常干净(或清晰的IMHO)的方式来做你所要求的事情


您需要做的是将
选项
对象转换为字典。这可以通过以下方式实现:

然后必须将字典中的所有值加载到局部变量中。我发现这显示了如何做到这一点的例子。我喜欢Ken的答案,因为它清晰明了:

for item in opt_dict.iteritems():
    eval('{0} = {1}'.format(*item))
但它允许危险输入潜入的可能性。此外,这必须在
getArguments()
函数之外完成

但是,我同意,对于前面链接的问题,公认的答案可能是最好的解决方法,即使用opt_dict更新全球数据


注意:如果像我怀疑的那样,您是在为Pig python包装器执行此操作,那么将变量加载到局部变量实际上会适得其反。变量需要作为字典传递到
bind

@MartijnPieters:很抱歉,复制粘贴时出现了输入错误。我正在返回输入。然后有一堆行基本上执行以下arg1=input.arg1作为清管器相关标记的代表,嘿!看起来您这样做是为了python包装器。欢迎在
Pig
中打开一个更具体的问题,我们需要更多关于这个主题的问题。@Ajeet:但是
options.arg1
有什么问题吗?这里不需要将所有选项重新分配给本地人。这样做没有什么真正的好处。options.arg1没有错,我想用arg1来代替:options.arg1使用
eval()
真是个糟糕的主意。如果OP需要globals(对于示例来说是这样),那么
globals().update(vars(parser.parse_args))
就足够了。我同意,我喜欢
eval
方法,因为在我看来,它更具可读性。我将强调答案中提到这是一个坏主意的部分。
for item in opt_dict.iteritems():
    eval('{0} = {1}'.format(*item))