diff --git a/sources/tech/20210816 Parse command-line arguments with argparse in Python.md b/sources/tech/20210816 Parse command-line arguments with argparse in Python.md deleted file mode 100644 index 5b6657fd1a..0000000000 --- a/sources/tech/20210816 Parse command-line arguments with argparse in Python.md +++ /dev/null @@ -1,168 +0,0 @@ -[#]: subject: "Parse command-line arguments with argparse in Python" -[#]: via: "https://opensource.com/article/21/8/python-argparse" -[#]: author: "Moshe Zadka https://opensource.com/users/moshez" -[#]: collector: "lujun9972" -[#]: translator: "MjSeven" -[#]: reviewer: " " -[#]: publisher: " " -[#]: url: " " - -Parse command-line arguments with argparse in Python -====== -Use the argparse module to enable options in your Python applications. -![Python options][1] - -There are several third-party libraries for command-line argument parsing, but the standard library module `argparse` is no slouch either. - -Without adding any more dependencies, you can write a nifty command-line tool with useful argument parsing. - -### Argument parsing in Python - -When parsing command-line arguments with `argparse`, the first step is to configure an `ArgumentParser` object. This is often done at the global module scope since merely _configuring_ the parser has no side effects. - - -``` -import argparse - -PARSER = argparse.ArgumentParser() -``` - -The most important method on `ArgumentParser` is `.add_argument()`. It has a few variants. By default, it adds an argument that expects a value. - - -``` -`PARSER.add_argument("--value")` -``` - -To see it in action, call the method `.parse_args()`: - - -``` -`PARSER.parse_args(["--value", "some-value"])`[/code] [code]`Namespace(value='some-value')` -``` - -It's also possible to use the syntax with `=`: - - -``` -`PARSER.parse_args(["--value=some-value"])`[/code] [code]`Namespace(value='some-value')` -``` - -You can also specify a short "alias" for a shorter command line when typed into the prompt: - - -``` -`PARSER.add_argument("--thing", "-t")` -``` - -It's possible to pass either the short option: - - -``` -`PARSER.parse_args("-t some-thing".split())`[/code] [code]`Namespace(value=None, thing='some-thing')` -``` - -or the long one: - - -``` -`PARSER.parse_args("--thing some-thing".split())`[/code] [code]`Namespace(value=None, thing='some-thing')` -``` - -### Types - -There are more types of arguments available. The two most popular ones, after the default, are boolean and counting. The booleans come with a variant that defaults to true, and one that defaults to false. - - -``` -PARSER.add_argument("--active", action="store_true") -PARSER.add_argument("--no-dry-run", action="store_false", dest="dry_run") -PARSER.add_argument("--verbose", "-v", action="count") -``` - -This means that `active` is `False` unless `--active` is passed, and `dry_run` is `True` unless `--no-dry-run` is passed. Short options without value can be juxtaposed. - -Passing all the arguments results in a non-default state: - - -``` -`PARSER.parse_args("--active --no-dry-run -vvvv".split())`[/code] [code]`Namespace(value=None, thing=None, active=True, dry_run=False, verbose=4)` -``` - -The default is somewhat less exciting: - - -``` -`PARSER.parse_args("".split())`[/code] [code]`Namespace(value=None, thing=None, active=False, dry_run=True, verbose=None)` -``` - -### Subcommands - -Though classic Unix commands "did one thing, and did it well," the modern tendency is to do "several closely related actions." - -The examples of `git`, `podman`, and `kubectl` can show how popular the paradigm is. The `argparse` library supports that too: - - -``` -MULTI_PARSER = argparse.ArgumentParser() -subparsers = MULTI_PARSER.add_subparsers() -get = subparsers.add_parser("get") -get.add_argument("--name") -get.set_defaults(command="get") -search = subparsers.add_parser("search") -search.add_argument("--query") -search.set_defaults(command="search") - -[/code] [code]`MULTI_PARSER.parse_args("get --name awesome-name".split())`[/code] [code]`Namespace(name='awesome-name', command='get')`[/code] [code]`MULTI_PARSER.parse_args("search --query name~awesome".split())`[/code] [code]`Namespace(query='name~awesome', command='search')` -``` - -### Anatomy of a program - -One way to use `argparse` is to structure the program as follows: - - -``` -## my_package/__main__.py -import argparse -import sys - -from my_package import toplevel - -parsed_arguments = toplevel.PARSER.parse_args(sys.argv[1:]) -toplevel.main(parsed_arguments) - -[/code] [code] - -## my_package/toplevel.py - -PARSER = argparse.ArgumentParser() -## .add_argument, etc. - -def main(parsed_args): - -    ... - -    # do stuff with parsed_args -``` - -In this case, running the command is done with `python -m my_package`. Alternatively, you can use the [`console_scripts`][2] entry points in the package's setup. - -### Summary - -The `argparse` module is a powerful command-line argument parser. There are many more features that have not been covered here. The limit is your imagination. - --------------------------------------------------------------------------------- - -via: https://opensource.com/article/21/8/python-argparse - -作者:[Moshe Zadka][a] -选题:[lujun9972][b] -译者:[译者ID](https://github.com/译者ID) -校对:[校对者ID](https://github.com/校对者ID) - -本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 - -[a]: https://opensource.com/users/moshez -[b]: https://github.com/lujun9972 -[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/bitmap_0.png?itok=PBXU-cn0 (Python options) -[2]: https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html#the-console-scripts-entry-point diff --git a/translated/tech/20210816 Parse command-line arguments with argparse in Python.md b/translated/tech/20210816 Parse command-line arguments with argparse in Python.md new file mode 100644 index 0000000000..b0f111acf9 --- /dev/null +++ b/translated/tech/20210816 Parse command-line arguments with argparse in Python.md @@ -0,0 +1,176 @@ +[#]: subject: "Parse command-line arguments with argparse in Python" +[#]: via: "https://opensource.com/article/21/8/python-argparse" +[#]: author: "Moshe Zadka https://opensource.com/users/moshez" +[#]: collector: "lujun9972" +[#]: translator: "MjSeven" +[#]: reviewer: " " +[#]: publisher: " " +[#]: url: " " + +Python 中使用 argparse 解析命令行参数 +====== +使用 argparse 模块为应用程序设置命令行选项。 +![Python options][1] + +有一些第三方库用于命令行解析,但标准库 `argparse` 与之相比也毫不逊色。 + +无需添加很多依赖,你就可以编写带有实用参数解析功能的漂亮命令行工具。 + +### Python 中的参数解析 + +使用 `argparse` 解析命令行参数时,第一步是配置一个 `ArgumentParser` 对象。这通常在全局模块内完成,因为单单_配置_一个解析器没有副作用。 + + +```python +import argparse + +PARSER = argparse.ArgumentParser() +``` + +`ArgumentParser` 中最重要的方法是 `.add_argument()`,它有几个变体。默认情况下,它会添加一个参数,并期望一个值。 + + +```python +PARSER.add_argument("--value") +``` + +查看实际效果,调用 `.parse_args()`: + + +```python +PARSER.parse_args(["--value", "some-value"]) +Namespace(value='some-value') +``` + +也可以使用 `=` 语法: + + +```python +PARSER.parse_args(["--value=some-value"]) +Namespace(value='some-value') +``` + +你还可以为短选项指定一个“别名”: + + +```python +PARSER.add_argument("--thing", "-t") +``` + +可以传入短选项: + + +```python +PARSER.parse_args("-t some-thing".split()) +Namespace(value=None, thing='some-thing') +``` + +或者长选项: + + +```python +PARSER.parse_args("--thing some-thing".split()) +Namespace(value=None, thing='some-thing') +``` + +### 类型 + +有很多类型的参数可供你使用。除了默认类型,最流行的两个是布尔类型和计数器。布尔类型默认为 true。 + + +```python +PARSER.add_argument("--active", action="store_true") +PARSER.add_argument("--no-dry-run", action="store_false", dest="dry_run") +PARSER.add_argument("--verbose", "-v", action="count") +``` + +除非显示传入 `--active`,否则 `active` 就是 `False`。`dry-run` 默认为是 `True`,除非传入 `--no-dry-run`。短选项可以并列。 + +传递所有参数会导致非默认状态: + + +```python +PARSER.parse_args("--active --no-dry-run -vvvv".split()) +Namespace(value=None, thing=None, active=True, dry_run=False, verbose=4) +``` + +默认值则比较单一: + + +```python +PARSER.parse_args("".split()) +Namespace(value=None, thing=None, active=False, dry_run=True, verbose=None) +``` + +### 子命令 + +经典的 Unix 命令秉承了“一次只做一件事,并做到极致”,但现代的趋势把“几个密切相关的操作”放在一起。 + +`git`、`podman` 和 `kubectl` 充分说明了这种范式的流行。`argparse` 库也可以做到: + + +```python +MULTI_PARSER = argparse.ArgumentParser() +subparsers = MULTI_PARSER.add_subparsers() +get = subparsers.add_parser("get") +get.add_argument("--name") +get.set_defaults(command="get") +search = subparsers.add_parser("search") +search.add_argument("--query") +search.set_defaults(command="search") + +MULTI_PARSER.parse_args("get --name awesome-name".split()) +Namespace(name='awesome-name', command='get') +MULTI_PARSER.parse_args("search --query name~awesome".split()) +Namespace(query='name~awesome', command='search')` +``` + +### 程序架构 + +使用 `argparse` 的一种方法是使用下面的结构: + +```python +## my_package/__main__.py +import argparse +import sys + +from my_package import toplevel + +parsed_arguments = toplevel.PARSER.parse_args(sys.argv[1:]) +toplevel.main(parsed_arguments) +``` + +```python +## my_package/toplevel.py + +PARSER = argparse.ArgumentParser() +## .add_argument, etc. + +def main(parsed_args): + + ... + + # do stuff with parsed_args +``` + +在这种情况下,使用 `python -m my_package` 运行。或者,你可以在包安装时使用 [`console_scprits`][2] 入口点。 + +### 总结 + +`argparse` 模块是一个强大的命令行参数解析器,还有很多功能没能在这里介绍。它能实现你想象的一切。 + +-------------------------------------------------------------------------------- + +via: https://opensource.com/article/21/8/python-argparse + +作者:[Moshe Zadka][a] +选题:[lujun9972][b] +译者:[MjSeven](https://github.com/MjSeven) +校对:[校对者ID](https://github.com/校对者ID) + +本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 + +[a]: https://opensource.com/users/moshez +[b]: https://github.com/lujun9972 +[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/bitmap_0.png?itok=PBXU-cn0 "Python options" +[2]: https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html#the-console-scripts-entry-point \ No newline at end of file