如何将字典作为命令行参数传递给Python脚本? [英] How to pass dictionary as command line argument to Python script?

查看:94
本文介绍了如何将字典作为命令行参数传递给Python脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字典作为命令行参数传递给Python脚本?我需要获取字典,其中键是字符串,值是某些元素的列表–例如:

  command_line_arguments = {:["J.J.","4月"],年".:[25,29]} 

我尝试过

 如果__name__ =='__main__':args = dict([sys.argv [2:]]中arg的[arg.split('='))#也尝试过1,但不起作用主(参数) 

我在叫类似的脚本

  $ python saver.py名称= ["J.J.","April"]年= [25,29] 

但是它不起作用,字典的长度为0,需要2.有人可以帮助我通过并在主目录中创建字典吗.

解决方案

此处要注意的重要一点是,在命令行中不能将python对象作为参数传递.您正在使用的当前Shell将解析参数,并根据其自身的参数解析规则将其传递.

话虽如此,您不能传入python字典.但是,诸如JSON之类的东西可以让您获得相当不错的收益.

JSON-或JavaScript对象表示形式是一种获取Python对象并将其转换为类似字符串的表示形式的方法,适合于传递给多种语言.话虽如此,您可以输入这样的字符串:

  python saver.py'{"names":["J.J.","April"],"years":[25,29]}' 

在您的python脚本中,执行以下操作:

  import json数据= json.loads(argv [1]) 

这将为您提供一个字典,该字典代表您想要传递的数据.

同样,您可以使用python字典并将其转换为字符串:

  import jsondata = {'names':["J.J.","April"],'years':[25,29]}data_str = json.dumps(数据) 

尽管JSON相当通用,但还有其他方法可以完成此操作.需要注意的关键是,无论您如何执行-都不会将字典传递给Python,-您将传递需要某种方式的一组参数(全都是字符串)转换为所需的python类型.

@EvanZamir-请注意,(通常)在外壳中,如果引号出现在加引号的字符串中,则需要对引号进行转义.在我的示例中,我用单引号将JSON数据引号,而JSON字符串本身使用双引号,从而消除了对引号的需要.

如果混合使用双引号(使用双引号将参数引起来,并在内部使用双引号),则外壳将要求将其转义,否则遇到的第一个双引号将被视为参数的闭引号".请注意,在示例中,我使用单引号将JSON字符串括起来,并在字符串内使用双引号.如果我在字符串中使用了单引号,则需要使用反斜杠对它们进行转义,即:

  python saver.py'{"names":["J.J.","April's"],"years":[25,29]}' 

  python saver.py"{\" names \:[\" J.J. \,\" April's \],\" years \:[25,29]}" 

请注意引号是Shell的功能,因此YMMV可能会有所不同(例如,如果您使用某种exec方法来调用脚本,则可能不需要转义,因为可能不会调用bash shell.)

How to pass dictionary as command line argument to Python script? I need to get dictionary where key is string and value is list of some elements – for example to look like:

command_line_arguments = {"names" : ["J.J.", "April"], "years" : [25, 29]}

I have tried like

if __name__ == '__main__':
    args = dict([arg.split('=') for arg in sys.argv[2:]]) # also tried with 1 but doesn't work
    main(args)

and I am calling script like

$ python saver.py names=["J.J.", "April"] years=[25, 29]

but it doesn't work, dictionary has length 0 and need 2. Can anyone help me to pass and create dictionary in main.

解决方案

The important thing to note here is that at the command line you cannot pass in python objects as arguments. The current shell you are using will parse the arguments and pass them in according to it's own argument parsing rules.

That being said, you cannot pass in a python dictionary. However, things like JSON can allow you to get pretty darn close.

JSON - or JavaScript Object Representation is a way of taking Python objects and converting them into a string-like representation, suitable for passing around to multiple languages. That being said, you could pass in a string like this:

python saver.py '{"names": ["J.J.", "April"], "years": [25, 29]}'

In your python script, do this:

import json
data=json.loads(argv[1])

This will give you back a dictionary representing the data you wanted to pass in.

Likewise, you can take a python dictionary and convert it to a string:

import json
data={'names': ["J.J.", "April"], 'years': [25,29]}
data_str=json.dumps(data)

There are other methods of accomplishing this as well, though JSON is fairly universal. The key thing to note is that regardless of how you do it - you won't be passing the dictionary into Python, - you'll be passing in a set of arguments (which will all be strings) that you'll need to somehow convert into the python type you need.

@EvanZamir - note that (generally) in a shell, you need to escape quotes if they appear in your quoted string. In my example, I quote the JSON data with single quotes, and the json string itself uses double quotes, thereby obviating the need for quotes.

If you mix quotes (use double quotes to quote the argument, and double quotes inside), then the shell will require it to be escaped, otherwise the first double quote it encounters is considered the "closing quote" for the argument. Note in the example, I use single quotes to enclose the JSON string, and double quotes within the string. If I used single quotes in the string, I would need to escape them using a backslash, i.e.:

python saver.py '{"names": ["J.J.", "April\'s"], "years": [25, 29]}'

or

python saver.py "{\"names\": [\"J.J.\", \"April's\"], \"years\": [25, 29]}"

Note the quoting stuff is a function of your shell, so YMMV might vary (for example, if you use some exec method to call the script, escaping might not be required since the bash shell might not be invoked.)

这篇关于如何将字典作为命令行参数传递给Python脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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