和其他编程语言一样,有没有办法在Pharo smalltalk或简单脚本中运行linux shell命令?我想让我的Pharo映像运行一个脚本,该脚本应该能够自动执行任务并将其返回到某个值。我看了几乎所有的文档,我找不到任何相关的东西。也许它不允许这样的功能。
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
值。
我同意eMBee的一份声明
把它归还给某个值
相当含糊。我正在添加有关I / O的信息。
你可能知道有三个基本的IO:stdin
,stdout
和stderr
。这些你需要与shell进行交互。我先添加这些示例,然后再回到您的描述中。
它们中的每一个都由Pharo中的AttachableFileStream
实例表示。对于上面的command
,你会得到initialStdIn
(stdin
),initialStdOut
(stdout
),initialStdError
(stderr
)。
从Pharo写入终端:
| 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你应该看到那里的输出。
| 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,合理的方法是使用qazxsw poi,从他的名字可以看出,它可以与管道一起使用。
简单的例子:
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.
就是这样。