Is it possible to use a string, instead of the output of a command, when using pipeline?
For example instead of writing
run(pipeline(`echo hello`, `sort`))
I would write something like
run(pipeline("hello", `sort`))
Is it possible to use a string, instead of the output of a command, when using pipeline?
For example instead of writing
run(pipeline(`echo hello`, `sort`))
I would write something like
run(pipeline("hello", `sort`))
Note that I tried doing
run(pipeline(`echo $("hello")`, `sort`))
which I believe would work but unfortunately echo is not available on Windows (despite it being available in cmd)
You can use open to write arbitrary Julia data to a pipeline or other command:
julia> open(pipeline(`cat`, `sort`), "w", STDOUT) do f
println(f, "hello")
end
hello
Thanks! This is still not fully clear to me. If I wanted to feed "hello" to the sort command, as above,what would I do, would I still need the pipeline function (what is the cat for here)?
Also, how would I capture back the output in a string?
The cat was only an example. If you just have sort, then you don’t need pipeline at all, just use
open(`sort`, "w", STDOUT)
If you want to read the output into a string, you can do:
stdout, stdin, process = readandwrite(`sort`)
println(stdin, "hello")
close(stdin)
readstring(stdout)
How did this became in 0.7?
Write to external program, which outputs to stdout:
julia> open(`sort`, "w", stdout) do f
print(f, "c\nb\na\n")
end
a
b
c
Read and write to external program:
f = open(`sort`, "r+")
print(f, "c\nb\na\n")
close(f.in)
read(f, String) # returns "a\nb\nc\n"
To follow up on this, you can now wrap the string with an IOBuffer and use it as the stdin argument to pipeline, which lets it be used by any function which takes a command, e.g.
julia> readlines(pipeline(`sort`,stdin=IOBuffer("c\nb\na\n")))
3-element Vector{String}:
"a"
"b"
"c"