将两个字符串传递给 Julia 中的外部实用程序 diff

Passing two strings to the external utility diff in Julia

我一直在尝试将两个字符串传递给 diff 命令行实用程序,因为它在 Julia 中具有图形化的并排比较功能。到目前为止,我的尝试包括以下内容:

s1 = "<very long multiline string 1>"
s2 = "<very long multiline string 2>"

# Results in LoadError: parsing command `diff -y <(echo $(s1)) <(echo $(s2))`:
# special characters "#{}()[]<>|&*?~;" must be quoted in commands
attempt1 = read(`diff -y <(echo $(s1)\) <(echo $(s2))`, String)

# Results in diff: extra operand '<(echo'
attempt2 = read(`diff -y \<\(echo $(s1)\) \<\(echo $(s2)\)`, String)

# Results in diff: missing operand after '<(echo
attempt3 = read(`diff -y "<(echo $(s1)) <(echo $(s2))"`, String)

# Results in diff: missing operand after '<(echo $(s1)) <(echo $(s2))'
attempt4 = read(`diff -y '<(echo $(s1)) <(echo $(s2))'`, String)

# Results in diff: <(echo <very long multiline string 1>: Filename too long
attempt5 = read(`diff -y \<\("echo $(s1)"\) \<\("echo $(s2)"\)`, String)

等等。字符串 s1s2 是在脚本执行期间生成的,因此不能作为文件访问。我试图用 bash “伪文件”语法

绕过它
diff -y <(command 1) <(command 2) ,

但 Julia 对命令字符串做了一些处理,因此它们不会像在 bash 中那样运行。那么,我如何在 Julia 中将两个字符串传递给 diff

是的,Julia 的 Cmdbash 不同。如果您不在 Windows,您可以使用 FIFOStreams.jl

模拟 bash 行为
using FIFOStreams
s1 = """
Humpty Dumpty sat on a wall,
Humpty Dumpty had a great fall.
All the king's horses and all the king's men
Couldn't put Humpty together again.
"""

s2 = """
Humpty Dumpty sat on a wall,
Humpty Dumpty had a great fall.
Four-score Men and Four-score more,
Could not make Humpty Dumpty where he was before.
"""

s = FIFOStreamCollection(2)
io = IOBuffer()

attach(s, pipeline(ignorestatus(`diff -y $(path(s, 1)) $(path(s, 2))`); stdout = io))

fs1, fs2 = s

print(fs1, s1)
print(fs2, s2)
close(s)

结果

julia> println(String(take!(io)))
Humpty Dumpty sat on a wall,                                    Humpty Dumpty sat on a wall
,
Humpty Dumpty had a great fall.                                 Humpty Dumpty had a great f
all.
All the king's horses and all the king's men                  | Four-score Men and Four-sco
re more,
Couldn't put Humpty together again.                           | Could not make Humpty Dumpt
y where he was before.