重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
這篇文章主要為大家展示了“python中如何使用click”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“python中如何使用click”這篇文章吧。
創新互聯是專業的灞橋網站建設公司,灞橋接單;提供成都做網站、成都網站建設、成都外貿網站建設,網頁設計,網站設計,建網站,PHP網站建設等專業做網站服務;采用PHP框架,可快速的進行灞橋網站開發網頁制作和功能擴展;專業做搜索引擎喜愛的網站,專業的做網站團隊,希望更多企業前來合作!
1.如何安裝
使用命令pip install click或者在PyCharm中安裝
2.隔離環境vitualenv
linux或MAC上
sudo pip install virtualenv
windows
pip install virtualenv
43如何激活
現在,每當您想要處理項目時,您只需激活相應的環境。在OS X和Linux上,執行以下操作:
$ . venv/bin/activate
如果您是Windows用戶,則以下命令適合您:
$ venv\scripts\activate
退出激活
$ deactivate
輸入以下命令以在virtualenv中激活Click:
$ pip install Click
4.click語法
函數通過裝飾來成為Click命令行工具 click.command()。最簡單的方法是,使用這個裝飾器裝飾一個函數會使它成為一個可調用的腳本:
import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo('Hello %s!' % name)
if __name__ == '__main__':
hello()
根據參數格式執行
$ python hello.py --count=3
Your name: John
Hello John!
Hello John!
Hello John!
自動生成幫助文檔
$ python hello.py --help
Usage: hello.py [OPTIONS]
Simple program that greets NAME for a total of COUNT times.
Options:
--count INTEGER Number of greetings.
--name TEXT The person to greet.
--help Show this message and exit.
6.打印函數click.echo
使用echo()而不是常規 print()函數?這個問題的答案是Click嘗試以相同的方式支持Python 2和Python 3
從Click 2.0開始,echo函數也對ANSI顏色有很好的支持
7.嵌套命令
使用@click.group()實現命令的嵌套,即可以存在子命令
@click.group()
def cli():
pass
@click.command()
def initdb():
click.echo('Initialized the database')
@click.command()
def dropdb():
click.echo('Dropped the database')
cli.add_command(initdb)
cli.add_command(dropdb)
正如您所看到的,group()裝飾器的工作方式與command() 裝飾器類似,但創建了一個Group對象,可以為其提供多個可以附加的子命令Group.add_command()。
對于簡單腳本,也可以使用Group.command()裝飾器自動附加和創建命令。上面的腳本可以這樣編寫:
@click.group()
def cli():
pass
@cli.command()
def initdb():
click.echo('Initialized the database')
@cli.command()
def dropdb():無錫人流多少錢 http://www.bhnnk120.com/
click.echo('Dropped the database')
然后,您將Group在setuptools入口點或其他調用中調用:
if __name__ == '__main__':
cli()
8.增加參數
添加參數@click.option要添加參數,請使用option()和argument()裝飾器:
@click.command()
@click.option('--count', default=1, help='number of greetings')
@click.argument('name')
def hello(count, name):
for x in range(count):
click.echo('Hello %s!' % name)
生成的幫助文檔如下
$ python hello.py --help
Usage: hello.py [OPTIONS] NAME
Options:
--count INTEGER number of greetings
--help Show this message and exit.
生成的幫助文檔如下
$ python hello.py --help
Usage: hello.py [OPTIONS] NAME
Options:
--count INTEGER number of greetings
--help Show this message and exit.
以上是“python中如何使用click”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注創新互聯行業資訊頻道!