【转载】Go执行命令行获取返回值(封装好的函数)

7 篇文章 0 订阅

本文转载自Go执行命令行获取返回值_赵克立博客_技术栈 ,链接地址 https://www.zhaokeli.com/article/8605.html ,原作者允许转载。


package main
import (
    "strings"
    "bytes"
    "os"
    "os/exec"
    "fmt"
)
func runCmd(cmdStr string) string{
    list := strings.Split(cmdStr, " ")
    cmd := exec.Command(list[0],list[1:]...)
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err := cmd.Run()
    if err != nil {
        return stderr.String()
    } else {
        return out.String()
    }
}
func main(){
    fmt.Println(runCmd("git --version"))
}

命令输出:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Socket封装的Java Redis工具类,可以用于执行Redis命令并获取返回值。 ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; public class RedisClient { private String host; private int port; private Socket socket; private BufferedReader reader; private OutputStream writer; public RedisClient(String host, int port) { this.host = host; this.port = port; } public void connect() throws IOException { socket = new Socket(host, port); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = socket.getOutputStream(); } public String sendCommand(String command) throws IOException { // 发送命令 writer.write(command.getBytes()); writer.write("\r\n".getBytes()); writer.flush(); // 读取返回值 StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { if (line.startsWith("+") || line.startsWith("-") || line.startsWith(":")) { // 状态回复、错误回复、整数回复 response.append(line.substring(1)).append("\n"); break; } else if (line.startsWith("$")) { // 批量回复 int length = Integer.parseInt(line.substring(1)); if (length == -1) { response.append("null\n"); } else { char[] buffer = new char[length]; reader.read(buffer); reader.read(); // 读取分隔符 response.append(new String(buffer)).append("\n"); } break; } else if (line.startsWith("*")) { // 多条批量回复 int count = Integer.parseInt(line.substring(1)); for (int i = 0; i < count; i++) { response.append(sendCommand("")); // 递归调用,读取每个元素 } break; } } return response.toString(); } public void close() throws IOException { socket.close(); } } ``` 使用方法如下: ```java RedisClient client = new RedisClient("127.0.0.1", 6379); client.connect(); String result = client.sendCommand("PING"); System.out.println(result); client.close(); ``` 上述代码会连接到本地的Redis服务器,并执行PING命令,然后打印返回值。你可以根据需要修改代码以适应其他Redis命令。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值