【问题标题】:Run shell command and return output as result of custom function运行 shell 命令并作为自定义函数的结果返回输出
【发布时间】:2010-06-07 06:18:23
【问题描述】:

我想编写一个自定义 OpenOffice 函数,该函数运行一个 shell 命令并将结果放入调用它的单元格中。我有一个基本的宏工作,但我找不到捕获命令输出的方法。

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

上面总是返回0。查看Shell 命令的文档,我认为它实际上并没有返回STDOUT。

我将如何捕获输出以便可以在我的函数中返回它?

【问题讨论】:

    标签: shell macros openoffice-calc openoffice-basic


    【解决方案1】:

    你能把输出重定向到一个临时文件,然后用另一个命令读入那个文件的内容吗?

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

    【讨论】:

      【解决方案2】:

      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())
      

      这会将命令的输出粘贴到活动文档的当前位置。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-08
        • 2011-12-11
        • 2021-02-24
        • 2014-11-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多