利用Click快速製作可運行的命令行並說明@click.argument其nargs=-1的用途- Python

Posted by: bart30508 | in Python | 1 week ago |

製作python的命令行,常見的就是利用Click Module,這個Package方法有很多,以下介紹常用的其中一種:

@clcik.command() + @click.argument

  1. @clcik.command():有了這個裝飾器,就能夠自定義命令,被裝飾的函數名就是命令名。

  2. @click.argument('test_names', nargs=-1):有了這個裝飾器,能夠為自定義命令添加參數,也就是在運行自定義命令,可以添加參數,並能夠傳入裝飾的函數中。

nargs有什麼用途?

根據官方文件說明:

nargs:The second most common version is variadic arguments where a specific (or unlimited) number of arguments is accepted. This can be controlled with the nargs parameter. If it is set to -1, then an unlimited number of arguments is accepted.

不懂沒關係,舉個例子:

@click.argument with nargs=-1:可傳入多個參數,就算被裝飾的函數只有一個參數

import click

@click.command()
@click.argument('filename',nargs=-1)
def touch(filename):
    """Print FILENAME."""
    for i in filename:
        click.echo(filename)

if __name__ == '__main__':
    touch()

image

加入nargs=-1,可以無限制傳入參數個數,並組成tuple給函數。

@click.argument without nargs=-1:只可傳入被裝飾的函數指定個數的參數

import click

@click.command()
@click.argument('filename')
def touch(filename):
    """Print FILENAME."""
    for i in filename:
        click.echo(filename)

if __name__ == '__main__':
    touch()

image

傳入超過函數指定的參數會報錯

Reference: https://click.palletsprojects.com/en/8.1.x/# https://stackoverflow.com/questions/57202736/where-should-i-implement-flask-custom-commands-cli https://blog.csdn.net/qq_40144132/article/details/108977696

Currently unrated
 or 

Subscribe

* indicates required

Recent Posts

Archive

2022
2021

Categories

Apache 1

Data Science 2

Dbfit 1

Design Pattern 1

Devops 3

DigitalOcean 1

Django 1

English 3

Excel 5

Flask 3

Git 1

HackMD 1

Heroku 1

Html/Css 1

Linux 4

Machine Learning 2

Manufacture 1

Mezzanine 18

Oracle 1

Postgresql 7

PowerBI 4

Powershell 4

Python 21

SEO 2

SQL Server 51

SQLite 1

Windows 1

database 8

work-experience 1

其他 1

自我成長 1

資料工程 1

Tags

SEO(1) Github(2) Title Tag(2) ML(1) 李宏毅(1) SQL Server(18) Tempdb(1) SSMS(1) Windows(1) 自我成長(2) Excel(1) python Flask(1) python(5) Flask(2)

Authors

bart30508 (146)

Feeds

RSS / Atom

利用Click快速製作可運行的命令行並說明@click.argument其nargs=-1的用途- Python

© COPYRIGHT 2011-2022. Max的文藝復興. ALL RIGHT RESERVED.