是否可以在 Pharo smalltalk 中编写 shell 命令?

Is it possible to write shell command within Pharo smalltalk?

像其他编程语言一样,Pharo smalltalk 或简单脚本中是否有 运行 linux shell 命令的方法?我想要我的 Pharo 图像 运行 一个应该能够自动执行任务的脚本,并且 return 它具有一定的价值。我查看了几乎所有的文档,但找不到任何相关的内容。也许它不允许这样的功能。

Pharo 允许 OS 交互。在我看来,最好的方法是使用 OSProcess(正如 MartinW 已经建议的那样)。

认为重复的人漏掉了这部分:

... running a script that should be able to automate a tasks and return it to some value...

invoking shell commands from squeak or pharo

中没有关于 return 值的内容

要获得 return 值,您可以按以下方式进行:

command := OSProcess waitForCommand: 'ls -la'.
command exitStatus.

如果你打印出上面的代码,你很可能会得到 0 作为成功。

如果你犯了一个明显的错误:

command := OSProcess waitForCommand: 'ls -la /dir-does-not-exists'.
command exitStatus.

在我的例子中你会得到 ~= 0512

编辑 添加更多细节以涵盖更多内容

我同意 eMBee 的声明

return it to some value

比较含糊。我正在添加有关 I/Os.

的信息

如您所知,存在三种基本 IO:stdinstdoutstderr。这些你需要与 shell 互动。我会先添加这些示例,然后再回到您的描述。

它们中的每一个都由 Pharo 中的 AttachableFileStream 实例表示。对于上面的 command 你会得到 initialStdIn (stdin), initialStdOut (stdout), initialStdError (stderr)。

写入终端来自 Pharo:

  1. stdoutstderr(将字符串流式传输到终端)

    | process |
    
    process := OSProcess thisOSProcess.
    process stdOut nextPutAll: 'stdout: All your base belong to us'; nextPut: Character lf.
    process stdErr nextPutAll: 'stderr: All your base belong to us'; nextPut: Character lf.
    

检查你的 shell 你应该在那里看到输出。

  1. stdin - 得到你输入的内容

    | userInput handle fetchUserInput |
    
    userInput := OSProcess thisOSProcess stdIn.
    handle := userInput ioHandle.
    "You need this in order to use terminal -> add stdion"
    OSProcess accessor setNonBlocking: handle.
    fetchUserInput := OS2Process thisOSProcess stdIn next.
    "Set blocking back to the handle"
    OSProcess accessor setBlocking: handle.
    "Gets you one input character"
    fetchUserInput inspect.
    

如果你想从命令intoPharo获取输出,一个合理的方法是使用PipeableOSProcess,从他的名字可以看出,可以与管道一起使用。

简单示例:

| commandOutput |

commandOutput := (PipeableOSProcess command: 'ls -la') output.
commandOutput inspect.

更复杂的示例:

| commandOutput |

commandOutput := ((PipeableOSProcess command: 'ps -ef') | 'grep pharo') outputAndError.
commandOutput inspect.

我喜欢使用 outputAndError 因为错别字。如果您的命令不正确,您将收到错误消息:

| commandOutput |

commandOutput := ((PipeableOSProcess command: 'ps -ef') | 'grep pharo' | 'cot') outputAndError.
commandOutput  inspect.

在这种情况下'/bin/sh: cot: command not found'

就是这样。

更新 29-3-2021 OSProcess 适用于 Pharo 7。它没有升级到可以工作Pharo 8 或更高版本的更改。