hzDocs
hzDocs
文章 / 文档hedzr.com首页

cmdr series

介绍 cmdr

Guide

你的首个 CLI app更适合工程实践的版本
循序渐进
基本概念
命令命令:执行外部程序命令:预设参数命令:重定向命令:动态命令清单命令:在配置文件中定义别名清单命令:事件响应函数标志标志:必须项标志:可翻转组标志:枚举值标志:`Head -1` 风格标志:调用外部工具获得输入标志:自动否定标志:加号 `+` 前缀标志:事件响应函数解析结果内建命令和标志帮助子系统可共享共存的 app 实例辨析顶级函数WithOptsBackstage
如何……
Auto-close the ClosersRead config into structUsing is DetectorsUsing Store

References

What's New
Packages

Others

Examples
Blueprint
产品发布
产品发布之前
介绍 cmdr-cxx

Guide

cmdr supports

Intro

Guide

More features

References

Others

evendeep(-go)

Guide

Usagesdeepcopydeepdiffdeepequal
logg/slog(-go)

Guide

Guide

others

Components
trie-cxx

Guide

Guide

links

On Github

命令:执行外部程序

Invoking program

执行外部程序、Shell 命令

.InvokeShell(shellCmdLine) 和 .UseShell(shellPath) 可以被用于执行 Shell 命令(例如 ls -la),后者可以附加指定采用哪一个 Shell,如果没有显式地指定则采用用户系统的默认 Shell。

.InvokeProc(program) 可以被用于执行一个外部可执行文件。

以 macOS 为例,.InvokeProc("say 'hello world'") 可以执行 say 命令并以语音方式读出“hello world”文本。

program 不应该是 Shell 命令,例如 bash 的 echo 命令是不能直接被用作 program 的,要使用 bash -c echo "hello" 的语法。

其典型的用途是执行一个 GUI app。

定义

examples/demo/ 展示了 invokeXXX 的用法,详见 cmd/invoke.go:

package main

import (
	"context"
	"os"

	"github.com/hedzr/cmdr/v2"
	"github.com/hedzr/cmdr/v2/cli"
	"github.com/hedzr/cmdr/v2/examples/cmd"
	logz "github.com/hedzr/logg/slog"
)

const (
	appName = "demo-app"
	desc    = ``
	version = cmdr.Version
	author  = ``
)

func main() {
	app := cmdr.Create(appName, version, author, desc).
    With(func(app cli.App) {
	  }).
    WithAdders(cmd.Commands...).
    Build()

	ctx := context.Background()
	if err := app.Run(ctx); err != nil {
		logz.ErrorContext(ctx, "Application Error:", "err", err) // stacktrace if in debug mode/build
		os.Exit(app.SuggestRetCode())
	} else if rc := app.SuggestRetCode(); rc != 0 {
		os.Exit(rc)
	}
}
package cmd

import (
	"github.com/hedzr/cmdr/v2/cli"
)

type invokeCmd struct{}

func (invokeCmd) Add(app cli.App) {
	app.Cmd("invoke").
		With(func(b cli.CommandBuilder) {
			b.Cmd("shell").InvokeShell(`ls -la`).UseShell("/bin/bash").OnAction(nil).Build()
			b.Cmd("proc").InvokeProc(`say "hello, world!"`).OnAction(nil).Build()
		})
}
package cmd

var Commands = []cli.Adder{
	jumpCmd{},
	wrongCmd{},
	invokeCmd{},
	presetCmd{},
}

运行时

上面的示例程序的运行时效果如同这样:

$ go run ./examples/demo invoke shell
... ls results ...
$ go run ./examples/demo invoke proc
(play voice with say)
$

额外的话题

Howto run a subcmd directly from root

Command

Command: Invokes

Command: Preset Args

Command: Redirect To

Command: Dynamic Cmd

Command: Dynamic Cmd From Config

Command: Event Handlers

What is Next?

Components

Components

On Github

How is this guide?

最后更新于

目录

执行外部程序、Shell 命令
定义
运行时
额外的话题