簡體   English   中英

是否可以在 Pharo smalltalk 中編寫 shell 命令?

[英]Is it possible to write shell command within Pharo smalltalk?

像其他編程語言一樣,有沒有辦法在 Pharo smalltalk 或簡單的腳本中運行 linux shell 命令? 我想讓我的 Pharo 圖像運行一個腳本,該腳本應該能夠自動執行任務並將其返回到某個值。 我查看了幾乎所有的文檔,但找不到任何相關的內容。 也許它不允許這樣的功能。

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.

在我的案例512您將獲得~= 0值。

編輯添加更多細節以涵蓋更多領域

我同意 eMBee 的聲明

將其返回到某個值

比較模糊。 我正在添加有關 I/O 的信息。

您可能知道有三個基本 IO: stdinstdoutstderr 這些你需要與shell交互。 我會先添加這些例子,然后我會回到你的描述。

他們每個人都用的實例表示AttachableFileStream在菲羅。 對於上述command您將獲得initialStdIn ( stdin )、 initialStdOut ( stdout )、 initialStdError ( stderr )。

寫入菲羅終端:

  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.

檢查您的外殼,您應該在那里看到輸出。

  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.

如果你想抓住命令的輸出一個菲羅合理的方式是使用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 或更新版本的更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM