2010-06-07 35 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()) 

这将在活动文档的当前点处的命令的输出粘贴。

请注意,如果该命令发出几行,“文本导入”对话框将弹出(我不知道如何防止)。

相关问题