与其他编程语言一样,有没有办法在 Pharo smalltalk 或简单脚本中运行 linux shell 命令?我想让我的 Pharo 图像运行一个脚本,该脚本应该能够自动执行任务并将其返回到某个值。我查看了几乎所有的文档,但找不到任何相关的内容。也许它不允许这样的功能。
最佳答案
Pharo 允许操作系统交互。在我看来,最好的方法是使用 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 中没有关于返回值的内容
要获得返回值,您可以按以下方式进行:
command := OSProcess waitForCommand: 'ls -la'.
command exitStatus.
如果你打印出上面的代码,你很可能会得到一个 0
作为成功。
如果你犯了一个明显的错误:
command := OSProcess waitForCommand: 'ls -la /dir-does-not-exists'.
command exitStatus.
在我的例子中你会得到 ~= 0
值 512
。
编辑添加更多细节以覆盖更多领域
我同意 eMBee 的声明
return it to some value
比较模糊。我正在添加有关 I/O 的信息。
如您所知,存在三种基本 IO:stdin
、stdout
和 stderr
。这些你需要与 shell 交互。我会先添加这些示例,然后再回到您的描述。
它们中的每一个都由 Pharo 中的 AttachableFileStream
实例表示。对于上面的命令
,你会得到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.
检查您的 shell,您应该在那里看到输出。
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'
就是这样。
更新 29-3-2021OSProcess 可运行到 Pharo 7。它未升级以适应 Pharo 8 或更高版本的更改。
关于linux - 是否可以在 Pharo smalltalk 中编写 shell 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51363155/