如何使用 AppleScript 将命令一个一个地发送到终端并保存输出,该输出不可写到文件中的任何地方?

How to send a command using AppleScript to terminal one by one and save the output, which is not writable to file anywhere?

那么,我有一个问题。我从网上下载了一个程序。这是一个命令行应用程序。我写了一段代码,它为应用程序生成了一些 n-k 命令。我已将它们写入输出文件。我可以在 Python 中编写一个应用程序,但它会在某些命令上冻结。我已经手动测试了它们,似乎有两个问题:

  1. 命令必须运行一个接一个;
  2. 有些命令会给出类似bla-bla-bla的输出,这个东西不会写入输出文件。所以,如果我 运行 命令 ./app -p /file1 -o /file2 -s -a smth- > /fileOutput.txt fileOutput.txt 是空的,虽然在终端中,有这条 bla-bla-bla 消息,说明有问题。如果命令给出 bla-bla-bla 应用程序可能会冻结一段时间。

这是我想要做的:

  1. CD 进入包含应用程序的文件夹;
  2. For command in fileWithCommands 执行命令并开始下一个,仅当上一个完成时;
  3. 如果命令给出消息,包含 bla-bla-bla(因为它可能看起来像 file1 bla-bla-bla),将命令和这个奇怪的输出写入文件 badOutputs.txt.

没用过applescript。然而,这就是我到目前为止所做的:

set theFile to "/Users/MeUser/Desktop/firstCommand"
set fileHandle to open for access theFile
set arrayCommand to paragraphs of (read fileHandle)
#I have found the previous code here: http://alvinalexander.com/mac-os-x/applescript-read-file-into-list-array-examples
close access fileHandle
tell application "Terminal"
    activate
    do script "cd /Users/MeUser/Desktop/anApp/"
    repeat with command in arrayCommand
        do script command
    end repeat
end tell

虽然有问题,但如果一个 window 命令组成一个巨大的队列。没有window 1 cd 和命令是不同的windows。而且我仍然无法保存输出。

更新

根据 @Mark Setchell 的建议做了。所以现在我有这样的代码:

set theFile to "/Users/meUser/Desktop/firstCommand"
set fileHandle to open for access theFile
set arrayCommand to paragraphs of (read fileHandle)
close access fileHandle
repeat with command in arrayCommand
    do shell script "cd /Users/meUser/Desktop/App/; " & command
end repeat

我在命令中添加了以下内容:

2>&1 /Users/meUser/Desktop/errorOut.txt

但是apple脚本说app的错误就是脚本的错误。即:文件损坏,应用程序失败。我希望它写入失败的错误文件并移动到下一个命令,而脚本只是失败。

也许不是一个完整的解决方案,但不仅仅是评论而且更容易以这种方式格式化...

第一期

您在终端上写入的命令行应用程序可能正在写入 stderr 而不是 stdout。尝试使用

stderr 重定向到与 stdout 相同的位置
./app -p ... > /FileOutput.txt 2>&1

第二期

你不能做:

do shell script cd somewhere
do shell script do_something

因为每个 do shell script 将在 一个单独的、不相关的进程 中执行。因此,您的第一个进程将在默认目录中启动 - 与所有进程一样 - 并正确更改目录然后退出。然后您的第二个进程将启动 - 像所有进程一样在默认目录中 - 并尝试 运行 您的命令。除了那样,您还可以这样做:

do shell script "cd somewhere; do_something"

它会启动一个更改目录的进程,然后 运行 将您的命令行程序放在那里。

第三期

你为什么要将命令发送到终端?用户是否需要在终端中看到一些东西——似乎不太可能,因为你想捕获输出,不是吗?你不能只 运行 你的命令使用 do shell script 吗?

第四期

如果您想将正常输出与错误输出分开,您可以这样做:

./app ... params ... > OutputFile.txt 2> errors.txt

建议1

您可以保留所有脚本中的所有错误并将它们累积在一个文件中,如下所示:

./app .. params .. >> results.txt 2>&1

这可能使您以后可以单独处理错误。

建议2

您可以将 shell 脚本的输出捕获到一个 Applescript 变量中,比如 ScriptOutput,像这样,然后您可以解析它:

set ScriptOutput to do shell script "..."

建议3

如果您的脚本导致的错误正在停止您的循环,您可以像这样将它们包含在 try block 中,以便它们得到处理并继续进行:

try
   do shell script "..."
on error errMsg
   display dialog "ERROR: " & errMsg
end try