首页 > 解决方案 > 如何通过 Smalltalk 中的 stdin、stdout、stderr 与子进程交互?

问题描述

此 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(复制-粘贴了来自网络的不同片段)等 - 成功率为零!结果是:

有人会告诉我简单的工作示例如何启动一个进程并发送命令,阅读答案,然后再次发送,等等在某个循环中 - 我计划在一个分离的线程中进行这样的通信并将它用作一些服务,因为 Pharo,Smalltalk 通常缺少大多数绑定,所以我将像过去那样使用子进程通信......

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

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

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

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

标签: smalltalkpharosqueak

解决方案


让我从PipeableOsProcess可能在 Windows 上坏掉的开始。我已经尝试过了,它只是打开了一个命令行,没有别的(它不会冻结我的 Pharo 8)。整体OSProcess在我眼中无法正常工作。

所以我拍了一张LibC应该不适用于Windows的照片。

我是一个定义对标准 LibC 的访问的模块。我在 Linux 和 OSX 下可用,但在 Windows 下不可用,原因很明显:)

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

该解决方案更像是使用文件的解决方法,是使用LibCand #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. 

推荐阅读