go - 如何将 exec.Command 的输出通过管道传输到 Golang 中的另一个命令

标签 go command-line-arguments psql

我有八个 Microsoft Access 数据库,每个数据库都有大约 215 个表,我需要将这些数据库传输到 postgresql,所以我使用 mdb-tools 并导出方案,这只是一步;但是当涉及到直接将表数据导出到 postgres 时在 postgresql 中,我必须为每个表编写此命令:

mdb-export -I postgres -q \' myaccessdatabase.mdb table-name | psql -d mypsqldatabase -U postgres -w -h localhost 

所以我一直在尝试编写一个go命令程序来做如下: 1. 首先执行命令列出表名。这将是下一个命令的参数。 2.然后开始for range循环执行一个导出tanle数据的命令,这个命令的输出是管道到下一个命令。 3. 这个命令是psql,它会写上一个命令的输出(这是sql插入语句)

package main

import (
    "bufio"
    "log"
    "os"
    "os/exec"
)
func main() {
    // command to Collect tables name and list it to the next command 
          tablesname := exec.Command("mdb-tables", "-1", "myaccessdatabase.mdb")

    // Run the command on each table name and get the output pipe/feed into the psql shell 
    for _, table := range tablesname {
        ls := exec.Command("mdb-export", "-I", "postgres", "-q", "\'", "myaccessdatabase.mdb", table)

        // | psql -d mydatabase -U postgres -w -h localhost command which will write each line from the output of previouse command's 
        visible := exec.Command("psql", "-d", "mypsqldatabase", "-U", "postgres", "-w", "-h", "localhost")



    }
}

所以我尝试将输出通过管道传输到下一个命令的标准输入中,但无法实现它,同时我正在尝试使用 goroutin,而 channel 甚至无法提供将其变成最后一个命令的方法。

非常感谢您。

最佳答案

exec.Command 函数只创建命令,并不执行它。

要从 tablesname := exec.Command("mdb-tables", "-1", "myaccessdatabase.mdb") 获取输出,您需要运行该命令并捕获其输出:

tablesname := exec.Command("mdb-tables", "-1", "myaccessdatabase.mdb")
//capture the output pipe of the command
outputStream := bufio.NewScanner(tablesname.StdoutPipe())
tablesname.Start()  //Runs the command in the background

for outputStream.Scan() {   
//Default scanner is a line-by-line scan, so this will advance to the next line
    ls := exec.Command("mdb-export", "-I", "postgres", "-q", "\'", "myaccessdatabase.mdb", outputStream.Text())
    ls.Run()  //Blocks until command finishes execution

    visible := exec.Command("psql", "-d", "mypsqldatabase", "-U", "postgres", "-w", "-h", "localhost")
    visible.Run()
}

tablesname.Wait()  //Cleanup 

注意:对于数据库交互,exec 不是惯用代码。

SQL 库允许与数据库直接交互:http://golang.org/pkg/database/sql/

关于go - 如何将 exec.Command 的输出通过管道传输到 Golang 中的另一个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32669237/

相关文章:

forms - 使用 http.NewRequest POST 数据失败

go - 如何在 Go 中获取 IP 地址 :Beego

c# - 我能否以原始形式(例如包括引号)获取我的申请的论据?

C 中的命令行选项

java - Windows JVM 命令行参数上的尾随星号在 cygwin bash shell 中被通配

sql - postgresql - 尝试将变量从命令行传递到 sql 脚本时出错

postgresql - 已安装 Postgres.app 但无法运行

xml - 使用属性作为动态节点的值映射 XML

go - 使用 golang 提取 TCP 负载中的自定义数据格式

postgresql - psql - 将命令结果保存到文件