Piping Julia function output to external command

I’ve found a wealth of information on how to pipe one external command to another, but I’m having trouble with piping the output of julia functions to external commands.

As a side note, I’m not sure how I’m suppose to format this post since back ticks are used for inline code on the forums and denote Cmd types in Julia. Therefore in my sample code I’m using single quotes. Any time you see single quotes in this post, I mean backticks

For example, run(pipeline('ls','cat')) works as I would expect: it prints the contents of the current directory to stdout.

Now, how would I do this with readdir() instead, I have no clue.

I’ve tried a few things without effect (other than errors) and most of the informaiton availible on line is terribly outdates ( ie run("Hello World" |> 'echo') absolutely doesn’t work).

run(readdri() |> ‘cat’)
readdir() |> run(‘cat’)

I’ve been working on this for days now, but most of what I’ve read is out dated and I’m out of ideas.

Also, I have seen Pipe(), however this seems to only be useful for capturing output.

You can simply open a command to write to, and write whatever you want to it as if the pipe were a file. For example:

open(`cat`, "w", stdout) do f
    for s in readdir()
        println(f, s)

(This is explained in the manual.)


If you want to send data to a long-running process, you can see the way I do it in Gaston.jl here: https://github.com/mbaz/Gaston.jl/blob/master/src/gaston_init.jl This code starts gnuplot in the background, and communication happens through the three pipes that connect to gnuplot’s STDIN, STDOUT and STDERR.

To send data to the process, you can do something like println(gstdin, data).

1 Like

Hello @mbaz Going slightly off topic, I have a small project in mind. This is to use the Raspberry Pi Sensor Hat, which has temperature, pressure, humidity sensors etc.
For a demonstration I thought of plotting graphs of sensor data which update every N seconds.
I guess your method of piping to STDIN would be useful for this?
Your thoughts are welcomed please.

It could be useful, but I’m unsure what you’re planning:

  • If the sensor hat outputs data to its STDOUT, then you can connect to it from your Julia program and read it from there. However, if the sensor software provides an API, I’d recommend using it instead.
  • For plotting the data, you’re better off using a plotting package; on a small computer like the Pi, I’d recommend a simple plotting package like Gaston.

In case it’s helpful, you can format backticks in quoted code by putting a larger number of backticks around the code. For example:

``run(pipeline(`ls`, `cat`))``

formats inline as run(pipeline(`ls`, `cat`)).

I typed the above code block as

``run(pipeline(`ls`, `cat`))``

and I typed the above code block as


and… you get the idea!