我正在尝试在 shell 和 swi-prolog 之间编写一个接口,所以我希望(最好)让文本一次一行出现,但我知道为什么这可能不可能。 Swi-prolog 有一个 shell 谓词,它将给出 shell 命令的输出,但我不知道如何将该输出设置为变量。让 swipl 获取输出并再次打印也可以。有什么想法吗?
您的 shell 可以将其结果写入文件。然后调用 swi-prolog 程序将文件内容读入字符串并根据您的喜好重新格式化。例如。使用 DCG 等工具选择输出的一部分作为您的值。
除非我错误地理解了你的问题,否则你想要的是另一种方式,即序言到 shell。
刚刚看到这个老问题,并且认为在没有有用答案的情况下不应该对它进行否决。
我想你想要的就是它
create_process/3
。您可以重定向 stdin
、stdout
和 stderr
。如果您只想获取脚本的输出,请关注 stdout
,但如果您还想将数据发送到 shell 程序,请使用 stdin
执行相同的操作。使用 stderr
获取错误消息。这是一个简单的示例,给出了 ls /
的输出:
run_shell_and_get_output(Program, Args, Output) :-
process_create(path(Program), Args, [stdout(pipe(Stream))]),
read_stream_to_codes(Stream, Codes),
string_codes(Output, Codes).
?- run_shell_and_get_output(ls, [/], Output).
Output = "Docker\nbin\nboot\ndev\netc\nhome\ninit\nlib\nlib32\nlib64\nlibx32\nlost+found\nmedia\nmnt\nopt\nproc\nroot\nrun\nsbin\nsnap\nsrv\nsys\ntmp\nusr\nvar\n".
您还可以将进程连接在一起:
?- process_create(path(ls), [/], [stdout(pipe(O))]),
process_create(path(tr), ['a-z', 'A-Z'], [stdin(stream(O)), stdout(pipe(O1))]),
read_stream_to_codes(O1, C),
string_codes(S, C).
S = "DOCKER\nBIN\nBOOT\nDEV\nETC\nHOME\nINIT\nLIB\nLIB32\nLIB64\nLIBX32\nLOST+FOUND\nMEDIA\nMNT\nOPT\nPROC\nROOT\nRUN\nSBIN\nSNAP\nSRV\nSYS\nTMP\nUSR\nVAR\n".
这是写入 shell 程序然后读取输出的示例。注意:
close/1
调用是必要的,否则它将挂起(或特别注意缓冲)。
?- process_create(path(tr), ['a-z', 'A-Z'], stdin(pipe(In)), stdout(pipe(Out))]),
write(In, hello),
close(In),
read_stream_to_codes(Out, Codes),
string_codes(String, Codes).
String = "HELLO".