Feeding Julia strings in pipe to external program


#1

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

#2

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)


#3

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

#4

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?


#5

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)

#6

How did this became in 0.7?


#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"