美文网首页
如何简单优雅的写命令行程序

如何简单优雅的写命令行程序

作者: 高明无思 | 来源:发表于2021-05-26 18:59 被阅读0次

使用python自带的sys.argv来获取命令行参数可谓是又臭又长,那么今天介绍一个库:typer,教你如何简单优雅的编写命令行程序.

文档地址

https://typer.tiangolo.com/

安装

    pip install typer

我们来简单实现一个剪刀石头布的游戏:
我们每次输入一种手势,电脑随机产生一种手势.输出结果.


image.png

代码如下:

shitoubu.py

#!/usr/bin/env python
# coding: utf-8
# Gao Ming Ming Create At 2021-05-26
# Description:some description


import typer
import random

hands = ["剪刀","石头","布"] # 姿势集合
# 赢的比赛的集合
win_collection = {
        "剪刀":"布",
        "石头":"剪刀",
        "布":"石头"
}
# 电脑随机产生出拳姿势
def ai_hand():
    return random.sample(hands,1)[0]

# 开始比赛,并输出结果
def compare(human:str):
    ai = ai_hand()

    if human == ai:
        typer.echo("你们都出:{},平局.".format(human))
    elif win_collection.get(human) == ai:
        typer.echo("人类赢的比赛:{} win {}".format(human,ai))
    else:
        typer.echo("电脑赢的比赛:{} win {}".format(ai,human))

if __name__ == "__main__":
    typer.run(compare)

执行:

python shitoubu.py 布
人类赢的比赛:布 win 石头

python shitoubu.py 布
电脑赢的比赛:剪刀 win 布

代码比较简单,就不做解释了,不懂可以问.

to be continued.

相关文章

网友评论

      本文标题:如何简单优雅的写命令行程序

      本文链接:https://www.haomeiwen.com/subject/vmxlsltx.html