首页 > 其他分享 >0144-Go-命令行子命令

0144-Go-命令行子命令

时间:2023-01-30 19:11:06浏览次数:56  
标签:fooCmd fmt Args Println flag 0144 命令行 Go os

环境

  • Time 2022-08-25
  • Go 1.19

前言

说明

参考:https://gobyexample.com/command-line-subcommands

目标

使用 Go 语言的命令行子命令。

示例

package main

import (
    "flag"
    "fmt"
    "os"
)

func main() {

    fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
    fooEnable := fooCmd.Bool("enable", false, "enable")
    fooName := fooCmd.String("name", "", "name")

    barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
    barLevel := barCmd.Int("level", 0, "level")

    if len(os.Args) < 2 {
        fmt.Println("expected 'foo' or 'bar' subcommands")
        os.Exit(1)
    }

    switch os.Args[1] {

    case "foo":
        fooCmd.Parse(os.Args[2:])
        fmt.Println("subcommand 'foo'")
        fmt.Println("  enable:", *fooEnable)
        fmt.Println("  name:", *fooName)
        fmt.Println("  tail:", fooCmd.Args())
    case "bar":
        barCmd.Parse(os.Args[2:])
        fmt.Println("subcommand 'bar'")
        fmt.Println("  level:", *barLevel)
        fmt.Println("  tail:", barCmd.Args())
    default:
        fmt.Println("expected 'foo' or 'bar' subcommands")
        os.Exit(1)
    }
}

总结

使用 Go 语言的命令行子命令。

附录

标签:fooCmd,fmt,Args,Println,flag,0144,命令行,Go,os
From: https://www.cnblogs.com/jiangbo4444/p/17077025.html

相关文章

  • 0134-Go-读取文件
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/reading-files目标使用Go语言读取文件。示例packagemainimport("bufio""fmt......
  • 0135-Go-写入文件
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/writing-files目标使用Go语言写入文件。示例packagemainimport("bufio""fmt......
  • 0136-Go-行过滤器
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/line-filters目标使用Go语言行过滤器。示例packagemainimport("bufio""fmt"......
  • 0137-Go-文件路径
    环境Time2022-08-25Go1.19前言说明参考:https://gobyexample.com/file-paths目标使用Go语言处理文件路径。示例packagemainimport("fmt""path......
  • Django django-rest-framework-simplejwt
    Django(75)django-rest-framework-simplejwt「建议收藏」发布于2022-09-1611:56:13阅读 2440 大家好,又见面了,我是你们的朋友全栈君。 前言由于之前我们一......
  • mongodb的安装与部署
    简介MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之间的......
  • Django-rest-framework框架/1-drf-drf入门规范
    一、Web应用模式在开发Web应用中,有两种应用模式:1.1前后端不分离之前学的,写的bbs项目,图书管理系统,用的是前后端混合开发。-后端人员,写后端,也要写【模板语法】--->xx.h......
  • Django shell交互模式操作数据库
    打开shell交互模式命令pythonmanage.pyshell新增数据先进入交互模式,再导入类,用create创建数据,最后save(不save也可以),完成后可在数据库表中查看到创建的数据查询数......
  • django 自定义模版过滤器
    虽然DTL给我们内置了许多好用的过滤器。但是有些时候还是不能满足我们的需求。因此Django给我们提供了一个接口,可以让我们自定义过滤器,实现自己的需求。模版过滤器必须要......
  • [LeetCode] 1329. Sort the Matrix Diagonally 将矩阵按对角线排序
    A matrixdiagonal isadiagonallineofcellsstartingfromsomecellineitherthetopmostroworleftmostcolumnandgoinginthebottom-rightdirectionu......