2010-06-07 67 views
3

我想編寫一個自定義的OpenOffice函數,該函數運行一個shell命令並將結果放入調用它的單元中。我有一個基本的宏工作,但我找不到捕獲命令輸出的方法。運行shell命令並返回作爲自定義函數結果的輸出

Function MyTest(c1) 
    MyTest = Shell("bash -c "" echo hello "" ") 
End Function 

以上總是返回0。看看Shell命令的文檔,我不認爲它實際上會返回STDOUT。

我將如何捕獲輸出以便我可以將其返回到我的函數中?

回答

1

你可以將輸出重定向到一個臨時文件,然後用另一個命令讀入該文件的內容?

例如,Shell("bash -c "" echo hello > tmp.txt "" ")

1

Kimbal Robinson's answer作品,但使用文件的缺點。它比較慢(與僅使用內存相比),並且之後必須刪除文件(儘管將它放在/ tmp中,它通常最終會自動刪除)。

一種替代方法是通過剪貼板具有數據中轉:

Dim myCommand As String 
myCommand = "echo hello world" 
Shell ("bash", 1, "-c "" " & myCommand & " | xclip -selection clipboard"" ", true) 
' setting the 4th parameter to true ensures that the Shell function will wait until ' 
' the command terminates before returning ' 

' then paste the content of the clipboard ' 
Dim dh As Object 
dh = createUnoService("com.sun.star.frame.DispatchHelper") 
dh.executeDispatch(StarDesktop.CurrentFrame, ".uno:Paste", "", 0, Array()) 

這將在活動文檔的當前點處的命令的輸出粘貼。

請注意,如果該命令發出幾行,「文本導入」對話框將彈出(我不知道如何防止)。

相關問題