第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 exec.Command 的輸出通過管道傳輸?shù)?Golang 中的另一個命令

如何將 exec.Command 的輸出通過管道傳輸?shù)?Golang 中的另一個命令

Go
茅侃侃 2021-11-08 16:15:18
我有八個 Microsoft Access 數(shù)據(jù)庫,每個數(shù)據(jù)庫大約有 215 個表,我需要將這些數(shù)據(jù)庫轉(zhuǎn)移到 postgresql 中,所以我使用了 mdb-tools 并導(dǎo)出了僅一步的方案;但是當涉及將表數(shù)據(jù)導(dǎo)出到 postgres 時,我將其直接導(dǎo)入到 postgresql 中必須為每個表編寫此命令:mdb-export -I postgres -q \' myaccessdatabase.mdb table-name | psql -d mypsqldatabase -U postgres -w -h localhost 所以我一直在嘗試寫一個go命令程序來做如下: 1.首先執(zhí)行一個命令來列出表名。這將是下一個命令的 arg。2.然后啟動range loop執(zhí)行一個導(dǎo)出tanle數(shù)據(jù)的命令,這個命令的輸出是管道到下一個命令。3.這個命令是psql,它將寫入上一個命令的輸出(即sql insert statment)package mainimport (    "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")    }}所以我試圖將輸出通過管道傳輸?shù)较乱粋€命令的標準輸入中,但無法實現(xiàn)它,同時我正在嘗試使用 gooutin 和通道,甚至無法將其變成最后一個命令。
查看完整描述

1 回答

?
慕后森

TA貢獻1802條經(jīng)驗 獲得超5個贊

該exec.Command函數(shù)只創(chuàng)建命令,不執(zhí)行它。


要從 獲取輸出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 

注意:對于數(shù)據(jù)庫交互,exec不是慣用代碼。


SQL 庫允許與數(shù)據(jù)庫直接交互:http : //golang.org/pkg/database/sql/


查看完整回答
反對 回復(fù) 2021-11-08
  • 1 回答
  • 0 關(guān)注
  • 355 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號