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 sysargv = 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 usefulprint('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是什么意思? 看这里:

-hprint help and usage message
-m:accept custom option value
-drun 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:

现在运行脚本:

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:

因此,这将选项和参数收集在单独的列表中。 关于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 sysvariant = '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 = argelif opt in ('-d', '--debug'):print('Setting --debug.')debug = Trueelif opt == '--variant':print('Setting --variant.')variant = argprint('VARIANT   :', variant)
print('DEBUG   :', debug)
print('OUTPUT    :', output_file)
print('REMAINING :', remainder)

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

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

We can even try running this script without any arguments:

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

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

python getopt_Python getopt相关推荐

  1. python中getopt函数_python getopt模块使用方法

    python中 getopt 模块,是专门用来处理命令行参数的 getop标准格式: 函数getopt(args, shortopts, longopts = []) shortopts 是短参数   ...

  2. Python中getopt函数用法

    参考文献 Python中getopt()函数的使用 简述 对于Python使用命令行的方式去运行Python时候,想要添加各种参数,而想要比较合理的去得到这些参数,就需要使用到Python中的geto ...

  3. python getopt_python 5种 statsPython中的getopt函数使用详解

    函数原型: getopt.getopt(args, shortopts, longopts=[]) 参数解释: args:args为需要解析的参数列表.一般使用sys.argv[1:],这样可以过滤掉 ...

  4. python getopt_python 之 分割参数getopt

    python 之 分割参数getopt os下有个方法walk,非常的好用,用来生成一个generator.每次可以得到一个三元tupple,其中第一个为起始路径,第二个为起始路径下的文件夹,第三个是 ...

  5. python getopts_linux bash shell 中getopts 命令 和 python 中 getopt 函数的比较总结

    在 python 中有个获取命令行参数的函数叫 getopt(args, shortopts, longopts=[]) 通常我们使用的时候是如下的形式: import sys import geto ...

  6. python getopterror_python3 getopt用法

    python channel_builder.py -s /Users/graypn/ -d /Users/graypn/Documents -m 7 --out=report/xx.html 参数也 ...

  7. python中getopt函数_Python中getopt()函数的使用

    在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能.目前有短选项和长选项两种格式.短选项格式为"-"加上单个字母选项:长选项为"--"加 ...

  8. python getopterror_python getopt抛出getopterror选项——mode不能有参数

    当我指定命令行选项时,getopt似乎不起作用,抛出异常,这个名为o.py的文件: import getopt import sys opts,args = getopt.getopt(sys.arg ...

  9. Python中getopt()函数的使用

    在运行程序时,可能需要根据不同的条件,输入不同的命令行选项来实现不同的功能.目前有短选项和长选项两种格式.短选项格式为"-"加上单个字母选项:长选项为"--"加 ...

最新文章

  1. mysql www.school.com_MySQL 基础学习
  2. 设计模式(访问者模式)
  3. 160 - 27 Cosh.1
  4. 新入行程序员须知的8件事
  5. javascript Date对象
  6. python中类的定义和使用_Python中类的定义与使用
  7. MySql5.7 直接拷贝数据文件后出现table xxx doesn’t exist
  8. 医疗大数据分析需考虑哪些因素
  9. Python 列表深浅复制详解
  10. hbuilderX里uniapp和php,使用 DCloud 工具 HBuilder X 开发 uni-app 项目踩过的一些坑
  11. 一键将知网CAJ文件转换成带书签的PDF
  12. cefsharp 网页另存为图片,CefSharp获取页面截图
  13. LeetCode 1055. 形成字符串的最短路径
  14. 华为android截屏快捷键,华为手机怎么截屏快捷键是什么
  15. 云原生会统领SaaS服务的原因
  16. 为什么点火信号叫KL15,蓄电池电压叫KL30
  17. 《高效学习法》思维导图——Jan
  18. 用.NET做DDNS动态域名解析和SSL证书申请
  19. 一个女人频繁做这些事,真的很爱你
  20. 心存美好,总将走过寒冬,春回人间

热门文章

  1. 【转】java枚举类型ENUM
  2. [转载] 【Python】Python3 字典 fromkeys()方法
  3. [转载] python 命名空间
  4. ESP分区重建,解决各种引导问题
  5. Java设计模式学习记录-解释器模式
  6. UE4删除C++Classes下的类
  7. Appium移动端自动化测试之元素定位(三)
  8. Tomcat报错:ERROR:transport error 202: gethostbyname: unknown host
  9. springMVC 全局异常处理
  10. asp.net多语言设置方法