Stream: helpdesk (published)

Topic: ✔ Alternative to `sprint`


view this post on Zulip Sergio Vargas (Apr 02 2024 at 23:30):

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)?

view this post on Zulip jar (Apr 02 2024 at 23:59):

julia> read(`date -u`)
32-element Vector{UInt8}:
 0x54
 0x75
 0x65
 0x20

view this post on Zulip Sergio Vargas (Apr 03 2024 at 00:24):

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[]

view this post on Zulip Gunnar Farnebäck (Apr 03 2024 at 05:47):

julia> read(pipeline(IOBuffer("foo bar"), `cat`), String)
"foo bar"

view this post on Zulip Gunnar Farnebäck (Apr 03 2024 at 05:51):

Btw, a seekstart(cin) in your previous example had accomplished the same thing.

view this post on Zulip Notification Bot (Apr 03 2024 at 15:22):

Sergio Vargas has marked this topic as resolved.

view this post on Zulip Sergio Vargas (Apr 03 2024 at 15:28):

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.

view this post on Zulip Gunnar Farnebäck (Apr 03 2024 at 17:39):

The pipeline docstring has some hints:

pipeline(from, to) is equivalent to pipeline(from, stdout=to) when from
is a command, and to pipeline(to, stdin=from) when from is another kind of data
source.


Last updated: Nov 22 2024 at 04:41 UTC