python getopt_Python getopt

python getopt

Parsing command line arguments is a very common task, python getopt module is one of the option to parse python command line arguments.

解析命令行参数是一项非常常见的任务,python getopt模块是解析python命令行参数的选项之一。

Python getopt (Python getopt)

  • Python getopt module is very similar in working as the C getopt() function for parsing command-line parameters.

    Python的getopt模块与C的getopt()函数用于解析命令行参数非常相似。
  • As this function is similar to C function and Unix getopt() function, users familiar with those conventions will find it very easy to use Python getopt module functions.

    由于此函数类似于C函数和Unix getopt()函数,因此熟悉这些约定的用户会发现使用Python getopt模块函数非常容易。

If you want a simpler module to parse command-line parameters, try argparse.

如果要使用更简单的模块来解析命令行参数,请尝试argparse

Python getopt函数 (Python getopt function)

getopt is the first function provided by the module with same name.

getopt模块提供的第一个同名功能。

It parses the command line options and parameter list. The signature of this function is mentioned below:

它解析命令行选项和参数列表。 该功能的签名如下所述:

getopt.getopt(args, shortopts, longopts=[])

Its arguments includes:

其参数包括:

  • args are the arguments to be passed.

    args是要传递的参数。
  • shortopts is the options this script accepts.

    shortopts是此脚本接受的选项。
  • Optional parameter, longopts is the list of String parameters this function accepts which should be supported. Note that the -- should not be prepended with option names.

    可选参数longopts是该函数接受的String参数的列表,应支持此参数。 请注意--不应在选项名称前加上。

Let us study this function using some examples.

让我们使用一些示例来研究此功能。

Python getopt示例 (Python getopt example)

Now this will be tricky at first glance. We will see a simple example which will be tricky but we will explain things afterwards.

现在乍看之下这将是棘手的。 我们将看到一个简单的示例,该示例将很棘手,但之后我们将对其进行解释。

Here is the code snippet:

这是代码片段:

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 a message or do something useful
    print('Something went wrong!')
    sys.exit(2)

In this example, we simply accepted some arguments. Before running the script, let’s establish our understanding on what happened here:

在此示例中,我们仅接受了一些参数。 在运行脚本之前,让我们对这里发生的事情建立理解:

  • In sys.argv[1:], we are using starting index as 1 as sys.argv[0] is the name of the script that we’re running which we need not access in our script.

    sys.argv[1:] ,我们使用起始索引作为1,因为sys.argv[0]是我们正在运行的脚本的名称,无需在脚本中访问。
  • Now, the getopt function takes in three parameters:
    the command-line argument list which we get from sys.argv[1:], a string containing all accepted single-character command-line options that the script accepts, and a list of longer command-line options that are equivalent to the single-character versions.

    现在,getopt函数接受三个参数:
    我们从sys.argv[1:]获得的命令行参数列表,一个包含脚本可接受的所有接受的单字符命令行选项的字符串,以及一个等效于单个字符串的较长命令行选项的列表字符版本。
  • If anything wrong happens with the getopt call, we can also catch the Exception and handle it gracefully. Here, we just exited the script execution.

    如果getopt调用发生任何错误,我们还可以捕获Exception并对其进行优雅处理。 在这里,我们只是退出了脚本执行。
  • As in any other commands in any operating system, it is wise to print details when a user runs a script incorrectly.

    与任何操作系统中的任何其他命令一样,明智的做法是在用户错误地运行脚本时打印详细信息。

So, what does the hm:d means? See here:

那么, hm:d是什么意思? 看这里:

-h
  print help and usage message
-m:
  accept custom option value
-d
  run the script in debug mode

The first and last options are defaults. We use a custom option as m:, notice the colon? Colon means that this option can get any type of value. Finally, the single-character versions are same as longer versions, h is same as help. You can mention any one.

第一个和最后一个选项是默认选项。 我们使用自定义选项作为m: :,注意冒号吗? 冒号表示此选项可以获取任何类型的值。 最后,单字符版本与较长版本相同, hhelp相同。 您可以提及任何一个。

Let’s run the script now:

Python getopt example, python command line arguments

现在运行脚本:

So, this collected the options and arguments in separate lists. The best part about getopt is that it allows us to gracefully manage any possible exceptions:

python getopt error

因此,这将选项和参数收集在单独的列表中。 关于getopt最好的部分是它使我们能够优雅地管理任何可能的异常:

About the my_file= flag, there is an important point to note. The my_file= flag must always be provided with an additional argument, exactly like the -m flag. This is described by an equals sign in my_file=.

关于my_file=标志,有一点需要注意。 必须始终为my_file=标志提供一个附加参数,就像-m标志一样。 这由my_file=的等号描述。

用于GNU样式解析的Python gnu_output() (Python gnu_output() for GNU style Parsing)

In Python 2.3, another function was added in getopt module called gnu_output(). This function is very similar to the original getopt() function except the fact that by default, GNU style scanning is used. Let’s see an example script on how to use this function:

在Python 2.3中,在getopt模块中添加了另一个函数gnu_output() 。 该函数与原始的getopt()函数非常相似,不同之处在于默认情况下使用GNU样式扫描。 让我们看一下有关如何使用此功能的示例脚本:

import getopt
import sys

variant = '1.0'
debug = False
output_file = 'my_file.out'

print('ARGV      :', sys.argv[1:])

options, remainder = getopt.gnu_getopt(
    sys.argv[1:], 'o:v', ['output=', 'debug', 'variant=',])
print('OPTIONS   :', options)

for opt, arg in options:
    if opt in ('-o', '--output'):
        print('Setting --output.')
        output_file = arg
    elif opt in ('-d', '--debug'):
        print('Setting --debug.')
        debug = True
    elif opt == '--variant':
        print('Setting --variant.')
        variant = arg

print('VARIANT   :', variant)
print('DEBUG   :', debug)
print('OUTPUT    :', output_file)
print('REMAINING :', remainder)

Before we establish an understanding, let’s run this script:

Python getopt GNU Output

在建立理解之前,让我们运行以下脚本:

We can even try running this script without any arguments:

Python getopt GNU Output No argument

我们甚至可以尝试运行不带任何参数的脚本:

This describes default values which are assigned to values when no arguments are passed.

这描述了没有传递参数时分配给值的默认值。

Don’t forget to try the argparse module if you want more flexibility.

如果您想要更大的灵活性,请不要忘记尝试argparse模块

In this lesson, we learned about various ways through which we can manage the command-line parameters with getopt module in Python.

在本课程中,我们学习了可以使用Python中的getopt模块管理命令行参数的各种方法。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/17508/python-getopt

python getopt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值