smalltalk - 如何在 Smalltalk 中通过其 stdin、stdout、stderr 与子进程交互?

标签 smalltalk pharo squeak

这段 Python 代码展示了如何调用 Windows 10 中的某个进程并向其发送字符串命令,通过进程的 stdin、stdout 管道读取其字符串响应:

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import *
>>> p = Popen("c:/python38/python.exe", stdin=PIPE, stdout=PIPE)
>>> p.stdin.write(b"print(1+9)\n")
11
>>> p.communicate()
(b'10\r\n', None)
>>>

如您所见,python.exe 进程返回 10 作为 print(1+9) 的答案。现在我想在 Pharo(或 Squeak)中做同样的事情:在 Windows 10 操作系统中 - 我想类似的东西,即简短、简单、易于理解、真正有效。

我安装了 OSProcess、ProcessWrapper(它们在 Pharo 中丢失了,而且奇怪的是我收到警告说它们没有标记为 Pharo 8.0,并且未检查它们是否可以在 Pharo 8.0 中工作,但没问题),并且我尝试了 ProcessWrapper、PipeableOSProcess (从网络上复制粘贴不同的片段)等 - 成功率为零!结果是:

  • 没有任何反应,python.exe 未启动
  • 虚拟机错误控制台已打开(Pharo 底部的白色控制台,通过 F2 菜单控制)
  • 不同的异常(exception)情况
  • 等等

有人可以向我展示如何启动一个进程并向其发送命令、读取答案、然后再次发送等等的简单工作示例吗?我计划在一个独立的线程中进行此类通信并使用它作为某些服务,因为 Pharo、Smalltalk 通常缺少大多数绑定(bind),所以我将使用子进程通信,就像“美好”的过去一样......

我知道如何调用命令并获取其输出:

out := LibC resultOfCommand: 'dir ', aDir.

但我谈论的是另一种情况:与正在运行的进程进行交互通信(例如,使用 SSH 或类似上面的示例 - python.exe)。

PS。也许甚至可以使用 LibC #pipe:mode 来做到这一点?

最佳答案

首先,PipeableOsProcess 在 Windows 上可能已损坏。我已经尝试过了,它只是打开了一个命令行,没有其他任何东西(它不会卡住我的 Pharo 8)。在我看来,整个 OSProcess 无法正常工作。

所以我尝试了 LibC,它应该不适用于 Windows。

I’m a module defining access to standard LibC. I’m available under Linux and OSX, but not under Windows for obvious reasons :)

接下来要说的是Python对Windows的支持可能比Pharo的好很多。

解决方案更像是使用文件的解决方法,是使用 LibC#runCommand: (我试图提出一个与您类似的示例如上所示):

| count command result outputFile errorFile  |

count := 9+1.  "The counting"
command := 'echo ', count asString. "command run at the command line"

outputFile := 'output'. "a file into which the output is redirected"
errorFile := 'error'. "a file where the error output is redirected "

result := LibC runCommand: command, "run the command "
    ' >', outputFile, "redirect the output to output file"
    ' 2>', errorFile.

"reading back the value from output file"
outputFile asFileReference contents lines.
"reading back the value from the error file - which is empty in this case" 
errorFile asFileReference contents lines. 

关于smalltalk - 如何在 Smalltalk 中通过其 stdin、stdout、stderr 与子进程交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65211786/

相关文章:

error-handling - 如何在 Pharo 中复制和粘贴错误消息?

smalltalk - 我们如何在不在 Playground 上实例化对象的情况下运行 pharo 程序?

smalltalk - 为什么我不应该在 Smalltalk 中存储到文字数组中?

smalltalk - 如何处理 Squeak FFI 中的多个指针级别(如 char**)

smalltalk - Object 类中#doesNotUnderstand 的实现如何导致在 Squeak smalltalk 中打开调试器?

smalltalk - 使用 Seaside continuations

smalltalk - 魅力和鹦鹉螺问题

smalltalk - Pharo:菜单错误

arrays - 吱吱声如何使用笔转到: and place:

oop - 从字符串动态创建选择器