📜  Python中的Optparse模块

📅  最后修改于: 2022-05-13 01:54:55.388000             🧑  作者: Mango

Python中的Optparse模块

Optparse模块使编写命令行工具变得容易。它允许在Python程序中进行参数解析。

  • optparse使处理命令行参数变得容易。
  • 它默认带有Python。
  • 它允许动态数据输入改变输出

代码:创建一个 OptionParser 对象。

Python3
import optparse
parser = optparse.OptionParser()


Python3
# import OptionParser class
# from optparse module.
from optparse import OptionParser
 
# create a OptionParser
# class object
parser = OptionParser()
 
# ass options
parser.add_option("-f", "--file",
                  dest = "filename",
                  help = "write report to FILE",
                  metavar = "FILE")
parser.add_option("-q", "--quiet",
                  action = "store_false",
                  dest = "verbose", default = True,
                  help = "don't print status messages to stdout")
 
(options, args) = parser.parse_args()


Python3
# import optparse module
import optparse
 
# define a function for
# table of n
def table(n, dest_cheak):
    for i in range(1,11):
        tab = i*n
         
        if dest_cheak:
            print(tab)
             
    return tab
 
# define a function for
# adding options
def Main():
    # create OptionParser object
    parser = optparse.OptionParser()
     
    # add options
    parser.add_option('-n', dest = 'num',
                      type = 'int',
                      help = 'specify the n''th table number to output')
    parser.add_option('-o', dest = 'out',
                      type = 'string',
                      help = 'specify an output file (Optional)')
    parser.add_option("-a", "--all",
                      action = "store_true",
                      dest = "print",
                      default = False,
                      help = "print all numbers up to N")
     
    (options, args) = parser.parse_args()
    if (options.num == None):
            print (parser.usage)
            exit(0)
    else:
            number = options.num
         
    # function calling
    result = table(number, options.print)
     
    print ("The " + str(number)+ "th table is " + str(result))
 
    if (options.out != None):
        # open a file in append mode
        f = open(options.out,"a")
         
        # write in the file
        f.write(str(result) + '\n')
 
# Driver code
if __name__ == '__main__':
     
    # function calling
    Main()



定义选项:

应该使用add_option()一次添加一个。每个 Option 实例代表一组同义的命令行选项字符串。

创建 Option 实例的方法是:

要定义只有一个短选项字符串的选项:

parser.add_option("-f", attr=value, ....)

并定义一个只有长选项字符串的选项:

parser.add_option("--foo", attr=value, ....)

标准选项操作:

标准选项属性:

这是在简单脚本中使用 optparse 模块的示例:

Python3

# import OptionParser class
# from optparse module.
from optparse import OptionParser
 
# create a OptionParser
# class object
parser = OptionParser()
 
# ass options
parser.add_option("-f", "--file",
                  dest = "filename",
                  help = "write report to FILE",
                  metavar = "FILE")
parser.add_option("-q", "--quiet",
                  action = "store_false",
                  dest = "verbose", default = True,
                  help = "don't print status messages to stdout")
 
(options, args) = parser.parse_args()


使用这几行代码,您的脚本用户现在可以在命令行上执行“常规操作”,例如:

 --file=outfile -q

让我们通过一个例子来理解:

代码:为 n 的打印表编写Python脚本。

Python3

# import optparse module
import optparse
 
# define a function for
# table of n
def table(n, dest_cheak):
    for i in range(1,11):
        tab = i*n
         
        if dest_cheak:
            print(tab)
             
    return tab
 
# define a function for
# adding options
def Main():
    # create OptionParser object
    parser = optparse.OptionParser()
     
    # add options
    parser.add_option('-n', dest = 'num',
                      type = 'int',
                      help = 'specify the n''th table number to output')
    parser.add_option('-o', dest = 'out',
                      type = 'string',
                      help = 'specify an output file (Optional)')
    parser.add_option("-a", "--all",
                      action = "store_true",
                      dest = "print",
                      default = False,
                      help = "print all numbers up to N")
     
    (options, args) = parser.parse_args()
    if (options.num == None):
            print (parser.usage)
            exit(0)
    else:
            number = options.num
         
    # function calling
    result = table(number, options.print)
     
    print ("The " + str(number)+ "th table is " + str(result))
 
    if (options.out != None):
        # open a file in append mode
        f = open(options.out,"a")
         
        # write in the file
        f.write(str(result) + '\n')
 
# Driver code
if __name__ == '__main__':
     
    # function calling
    Main()

输出:

python file_name.py -n 4

python file_name.py -n 4 -o

文件.txt 创建

python file_name.py -n 4 -a

要了解有关此模块的更多信息,请单击此处。