pharo允许操作系统交互。在我看来,最好的方法是
OSProcess
(作为
MartinW
已经建议)。
那些认为这是复制品的人,却缺少了这一部分:
…运行应该能够自动执行任务和
把它还给某个值…
在
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
是的。
编辑
添加更多细节以覆盖更多地面
我同意埃贝的说法
把它还给某个值
相当模糊。我正在添加有关I/O的信息。
如您所知,有三种基本IO:
stdin
我是说,
stdout
,和
stderr
是的。这些你需要与shell交互。我将先添加这些示例,然后再回到您的描述。
它们中的每一个都由
AttachableFileStream
在法罗。为上述目的
command
你会得到
initialStdIn
(
标准物质
)我是说,
initialStdOut
(
标准输出
)我是说,
initialStdError
(
标准错误
)中。
写作
进入之内
终点站
从
法罗:
-
标准输出
和
标准错误
(将字符串流到终端)
| 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.
检查你的外壳你应该看到那里的输出。
-
标准物质
-得到你输入的内容
| 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.
如果要获取输出
从
指挥部
进入之内
法罗一个合理的方法是
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'
就这样。