且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python文件关键字参数?

更新时间:2022-04-16 03:53:29

我认为您正在寻找的是argparse模块

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.

例如假设script.py

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

现在,如果您尝试:

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

您将看到:

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

作为输出.我想这就是你的追求.

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

但是请阅读文档,因为这是有关如何使用argparse的 非常 的示例.例如,我传入的"3"和"4"被视为str而不是整数

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