Python - 命令行参数

Python - 命令行参数 首页 / Python3入门教程 / Python - 命令行参数

Python支持可以在命令行上运行的程序,并带有命令行参数。输入参数在执行时需要传递给脚本。

这意味着要与脚本的命令行界面进行交互。

它提供了一个 getopt 模块,可以在其中解析命令行参数和选项。

Sys模块

从早期开始,它是Python发行版附带的基本模块。这与使用argc/argv访问参数的C库类似。 sys模块在名为sys.argv的简单列表结构中实现命令行参数。

每个列表元素代表一个参数。第一个-sys.argv [0]-是Python脚本的名称。其他列表元素是sys.argv [1]到sys.argv [n]-是命令行参数2到n。作为参数之间的分隔符,使用了空格。因此,必须对其中包含空格的参数值进行引用。

它将命令行参数存储到列表中;无涯教程可以使用 sys.argv 访问它。这非常有用,并且是一种将命令行参数读取为String的简单方法。

import sys
print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)

Getopt模块

Python getopt模块通过参数验证扩展了输入字符串的分隔。基于getopt C函数,它允许长短选项,包括值分配。

与解析命令行参数的C getopt()函数非常相似。

它在解析命令行参数时非常有用,希望用户在此输入一些选项。

import getopt
import sys
argv = sys.argv[1:]
try:
    opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
    print(opts)
    print(args)
except getopt.GetoptError:
    # 打印消息或做一些有用的东西
    print('Something went wrong!')
    sys.exit(2)

Argparse模块

它提供具有标准化输出的命令行界面,而前两种解决方案将大部分工作交给您。 argparse允许使用UNIX或GNU样式的名称检查来验证固定和可选参数。这是解析命令行参数的首选方法。它提供了很多选项,例如位置参数,参数的默认值,帮助消息,指定参数的数据类型等。

getopt.getopt方法

此方法用于解析命令行选项和参数列表。

getopt.getopt(args, options, [long_options])

args                                -  这是一个需要解析的参数列表。

options                         -  脚本要识别的一串选项字母,其中的选项需要一个参数,后跟一个冒号(:)。

long_options(可选)  -  它必须是一个包含long选项名称的字符串。

getopt.GetoptError 异常

当在参数列表中找到无法识别的选项时,或者没有给任何需要参数的选项时,就会出现此异常。

异常的参数是指示错误原因的字符串。属性 msg opt 给出错误消息和相关选项。

#!/usr/bin/python
import sys, getopt
def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
   main(sys.argv[1:])

输出:

$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>

$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>

$ test.py -i inputfile
Input file is " inputfile
Output file is "

命令行参数

ModuleUsePython version
syssys.argv中的所有参数(基本)All
argparse建立命令行界面>= 2.3
docopt创建的命令行界面>= 2.5
fire自动生成命令行界面(CLI)All
optparseDeprecated< 2.7

Docopt用于创建命令行界面。

from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Example 1')
print(arguments) 

Python Fire自动生成命令行界面;您只需要一行代码。与其他模块不同,它可以立即工作。

您不需要定义任何参数。默认情况下,所有方法都是链接的。

要安装它,请输入:

pip install fire

定义或使用一个类:

import fire
class Python(object):
    def hello(self):
    print("Hello")
       def openfile(self, filename):
        print("Open file '" + filename + "'")

if __name__ == '__main__':
    fire.Fire(Python) 

您具有与类方法匹配的选项:

python example.py hello
python example.py openfile filename.txt

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Nginx核心知识150讲 -〔陶辉〕

Flutter核心技术与实战 -〔陈航〕

研发效率破局之道 -〔葛俊〕

高并发系统设计40问 -〔唐扬〕

Netty源码剖析与实战 -〔傅健〕

编译原理实战课 -〔宫文学〕

A/B测试从0到1 -〔张博伟〕

基于人因的用户体验设计课 -〔刘石〕

Serverless进阶实战课 -〔静远〕

好记忆不如烂笔头。留下您的足迹吧 :)