python关键字参数_Python文件关键字参数?

In command line I am able to pass arguments to a python file as:

python script.py arg1 arg2

I can than retrieve arg1 and arg2 within script.py as:

import sys

arg1 = sys.argv[1]

arg2 = sys.argv[2]

However, I would like to send keyword arguments to a python script, and retrieve them as a dictionary:

python script.py key1=value1 key2=value2

Then I would like to access the keyword arguments as a dictionary within python:

{'key1' : 'value1', 'key2' : 'value2'}

Is this possible?

解决方案

I think what you're looking for is the argparse module https://docs.python.org/dev/library/argparse.html.

It will allows you to use command line option and argument parsing.

e.g. Assume the following for script.py

import argparse

if __name__ == '__main__':

parser = argparse.ArgumentParser()

parser.add_argument('--arg1')

parser.add_argument('--arg2')

args = parser.parse_args()

print args.arg1

print args.arg2

my_dict = {'arg1': args.arg1, 'arg2': args.arg2}

print my_dict

Now, if you try:

$ python script.py --arg1 3 --arg2 4

you will see:

3

4

{'arg1': '3', 'arg2': '4'}

as output. I think this is what you were after.

But read the documentation, since this is a very watered down example of how to use argparse. For instance the '3' and '4' I passed in are viewed as str's not as integers

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值