python定义变量参数,命令行参数作为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

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

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.

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

解决方案

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)

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值