命令行参数作为Python中的变量定义 [英] Command line arguments as variable definition in Python

查看:202
本文介绍了命令行参数作为Python中的变量定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建(某种模板/包装器)脚本,该脚本使用一些未定义的选项来调用

I'm trying to construct a (kind of template/wrapper) script, which is called with some undefined options

> the_script.py --foo=23 --bar=42 --narf=fjoord

然后创建一个名为 foo = 23 bar = 42 narf ='fjoord'的变量

which then creates a variable called foo=23, bar=42, narf='fjoord' inside it.

该怎么做?我尝试使用 getopt ,但是它需要第二个参数,因此我必须定义要获取的选项,当然,我希望能够通过命令定义变量名线。我也尝试过 OptionParser ,虽然不确定如何处理未定义的选项。

What's the way to do it? I tried with getopt, but it needs a second parameter, so I have to define which options to get and of course, I want to be able to define my variable names via command line. I tried OptionParser too, not sure how to deal with undefined options though.

手动解析方法 sys.argv ,或者那里是否有一个模块,其功能完全相同?

So is the way manually parsing the sys.argv, or is there maybe a module out there, which does exactly the same thing?

推荐答案

这是一个相对简单的任务,具有 ast.literal_eval 和字符串拆分-但是只有在您定义的语法非常正确的情况下。 (例如,仅允许使用-foo = bar -foo bar 中的1个)。

This is a relatively simple task with ast.literal_eval and string splitting -- But only if you have a really well defined syntax. (e.g. only 1 of --foo=bar or --foo bar is allowed).

import argparse
import ast

parser = argparse.ArgumentParser() #allow the creation of known arguments ...

namespace,unparsed = parser.parse_known_args()

def parse_arg(arg):
    k,v = arg.split('=',1)
    try:
        v = ast.literal_eval(v) #evaluate the string as if it was a python literal
    except ValueError:          #if we fail, then we keep it as a string
        pass

    return k.lstrip('-'),v

d = dict(parse_arg(arg) for arg in unparsed)
print(d)

我将键值对放入字典中。如果您确实希望将它们用作全局变量,则可以执行 globals()。update(d)-但我会对此提出严重建议。

I've put the key-value pairs in a dictionary. If you really want them as global variables, you could do globals().update(d) -- But I would seriously advise against that.

这篇关于命令行参数作为Python中的变量定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆