I need to write to an external program and read its output, as an array of bytes.
I could do:
input_data = "foo bar"
cout = IOBuffer()
open(`cat`, "w", cout) do cin
write(cin, input_data)
end
output = take!(cout)
Or I could do:
output = sprint() do cout
open(`cat`, "w", cout) do cin
write(cin, input_data)
end
end
Is there a function like sprint
that returns the bytes like take!
does? Or better yet, is there a function that I can just call like output = f(`cmd`, input_data)
?
julia> read(`date -u`)
32-element Vector{UInt8}:
0x54
0x75
0x65
0x20
That works if the command doesn't read anything, but if I try to write something to its stdin, I don't get anything back:
julia> cin = IOBuffer();
julia> write(cin, "foo bar")
7
julia> read(pipeline(`cat`; stdin=cin))
UInt8[]
julia> read(pipeline(IOBuffer("foo bar"), `cat`), String)
"foo bar"
Btw, a seekstart(cin)
in your previous example had accomplished the same thing.
Sergio Vargas has marked this topic as resolved.
Thanks @Gunnar Farnebäck . Neither the docs nor the posts I had read on discourse showed that you could simply pass the IOBuffer
as an argument. That's much more convenient than the stdio kwargs.
The pipeline
docstring has some hints:
pipeline(from, to)
is equivalent topipeline(from, stdout=to)
whenfrom
is a command, and topipeline(to, stdin=from)
whenfrom
is another kind of data
source.
Last updated: Dec 28 2024 at 04:38 UTC