像其他编程语言一样,有没有办法在 Pharo smalltalk 或简单的脚本中运行 linux shell 命令?我想让我的 Pharo 图像运行一个脚本,该脚本应该能够自动执行任务并将其返回到某个值。我查看了几乎所有的文档,但找不到任何相关内容。也许它不允许这样的功能。
1 回答
Pharo 确实允许操作系统交互。在我看来,最好的方法是使用OSProcess
(正如MartinW已经建议的那样)。
那些认为它是重复的人缺少这部分:
...运行一个应该能够自动执行任务并将其返回到某个值的脚本...
从 squeak 或 pharo 调用 shell 命令中没有返回值
要获得返回值,您可以通过以下方式进行:
command := OSProcess waitForCommand: 'ls -la'.
command exitStatus.
如果您打印出上面的代码,您很可能会获得0
成功。
如果你犯了一个明显的错误:
command := OSProcess waitForCommand: 'ls -la /dir-does-not-exists'.
command exitStatus.
在我的情况下,您将获得~= 0
价值512
。
编辑添加更多细节以覆盖更多领域
我同意 eMBee 的说法
将其返回到某个值
比较模糊。我正在添加有关 I/O 的信息。
您可能知道有三个基本 IO: stdin
、stdout
和stderr
. 这些你需要与 shell 交互。我将首先添加这些示例,然后再返回您的描述。
它们中的每一个都由AttachableFileStream
Pharo 中的实例表示。对于上述内容,command
您将得到initialStdIn
( stdin
)、initialStdOut
( stdout
)、initialStdError
( stderr
)。
从Pharo写入终端:
stdout和stderr(您将字符串流式传输到终端)
| 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.
检查你的外壳,你应该在那里看到输出。
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.
如果你想从命令中获取输出到Pharo 中,一种合理的方法是使用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'
就是这样。
2021年 3月 29 日更新 OSProcess可以工作到 Pharo 7。它没有升级为与 Pharo 8 或更高版本的更改一起工作。