我有一個shell 指令(例如journalctl -f -o json
),它不斷地將行流傳輸到標準輸出。
我想逐行檢索此輸出並進一步處理。
os/exec
的文件解決如何讀取指令的輸出,io
處理流緩衝。
在我看來,處理過程都經過一個固定的緩衝區,該緩衝區被讀入、處理和進一步寫入。我的問題是該緩衝區的大小是固定的並且與內容無關。
有沒有辦法逐行讀取傳入流(在我的例子中是 shell 指令的輸出)?可能有比 io
讀者更進階的函式庫?
正確答案
使用cmd.stdoutpipe()
取得(管道)使用cmd.start()
啟動該進程之前的輸出( start()
啟動命令但不等待其完成)。
並使用 bufio.scanner
讀取輸入 (io.reader
) 行 -逐行。
例如,我將使用這個 bash 腳本列印當前時間 3 次,並在每次之間睡眠 1 秒:
for i in {1..3}; do date; sleep 1; done
執行此命令並逐行讀取其輸出的範例:
cmd := exec.command("bash", "-c", "for i in {1..3}; do date; sleep 1; done") out, err := cmd.stdoutpipe() if err != nil { log.fatal(err) } defer out.close() err = cmd.start() if err != nil { log.fatal(err) } scanner := bufio.newscanner(out) for scanner.scan() { line := scanner.text() fmt.println("output:", line) }
範例輸出:
2022/11/29 14:38:48 Output: Tue Nov 29 02:38:48 PM CET 2022 2022/11/29 14:38:49 Output: Tue Nov 29 02:38:49 PM CET 2022 2022/11/29 14:38:50 Output: Tue Nov 29 02:38:50 PM CET 2022
(每行開頭的第一個日期時間來自log
包,以驗證每行在第二次延遲後列印,另一個時間戳記是date
命令的輸出。)
以上是是否存在將程式的輸出作為流逐行讀取的概念?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。