Python 命令行参数

Python 命令行参数是执行它们时传递给脚本的输入参数. 几乎所有编程语言都支持命令行参数。

Python 命令行参数

阅读 python 命令行参数有很多选项,最常见的三个参数是:

  1. Python sys.argv
  2. Python getopt 模块
  3. Python argparse 模块

让我们通过简单的程序来学习如何阅读和使用 Python 命令行参数。

Python Sys 模块

Python sys 模块将命令行参数存储在列表中,我们可以使用 sys.argv 访问它. 这是阅读命令行参数作为 String 的非常有用的和简单的方法。

1import sys
2
3print(type(sys.argv))
4print('The command line arguments are:')
5for i in sys.argv:
6    print(i)

Below image illustrates the output of a sample run of above program. read python command line argument using sys.argv There are many other useful functions in sys module, read them in detail at python sys module.

Python 调试模块

Python getopt 模块在处理命令行参数时非常类似于 C `getopt() 函数。 Python getopt 模块在处理命令行参数时非常有用,我们希望用户也输入一些选项。

 1import getopt
 2import sys
 3
 4argv = sys.argv[1:]
 5try:
 6    opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
 7    print(opts)
 8    print(args)
 9except getopt.GetoptError:
10    # Print a message or do something useful
11    print('Something went wrong!')
12    sys.exit(2)

Above example is very simple, but we can easily extend it to do various things. For example, if help option is passed then print some user friendly message and exit. Here getopt module will automatically parse the option value and map them. Below image shows a sample run. parse command line argument in python using getopt module To learn more, read python getopt module.

Python 模块

Python argparse 模块是解析命令行参数的首选方式,它提供了许多选项,如位置参数、参数的默认值、帮助消息、指示参数的数据类型等。

1import argparse
2
3parser = argparse.ArgumentParser()
4parser.parse_args()

Below is the output from quick run of above script. python command line arguments using argparse module Python argparse module provide a lot many features, you should read about them at python argparse tutorial for clear understanding. That's all for different options to read and parse command line arguments in python, you should decide which is the one for your specific requirements and then use it. References:

Published At
Categories with 技术
Tagged with
comments powered by Disqus