How to redirect the output of run to a file

question

#1

MWE: suppose I wanted to do something equivalent to the shell command

ls /tmp > /tmp/list

in Julia. I came up with

open(io->run(pipeline(`ls /tmp`, stdout=io)), "/tmp/list", "w")

but I fear that I am overcomplicating it.


#2

So, is there an answer to that question? I just came across that issue and I am wondering how to redirect in a run command.


#3

You can use the @capture_out macro from Suppressor.jl, then write it to a file:

using Suppressor

output = @capture_out run(`ls`)

open("/var/log/myprogram.txt", "w") do io
    write(io, output)
end

#4

Ah, thanks, interesting. This looks complicated though.

The following seems to work, but I am not sure how to deal with more complex commands (e.g. with &> etc)

  run(pipeline(`ls /tmp`, stdout = "/tmp/list"))

The |> operator used to work for redirection, but the feature seems to have been removed.


#5

This is the most julian:

julia> open("out.txt", "w") do file                      
           write(file, readstring(`ls -l`))              
       end                                               
383                                                      
                                                         
shell> cat out.txt                                       
total 13                                                 
-rw-r--r-- 1 Ismael 197609 1203 Nov  4 00:17 LICENSE.md  
-rw-r--r-- 1 Ismael 197609  791 Nov  4 05:44 README.md   
-rw-r--r-- 1 Ismael 197609   25 Nov  4 00:17 REQUIRE     
-rw-r--r-- 1 Ismael 197609 2195 Nov  4 00:17 appveyor.yml
-rw-r--r-- 1 Ismael 197609    0 Nov  4 12:40 out.txt     
drwxr-xr-x 1 Ismael 197609    0 Nov  4 00:17 src         
drwxr-xr-x 1 Ismael 197609    0 Nov  4 00:17 test        

#6

Nice. Even shorter:

    write("output.txt", readstring(`ls -l`))

#7

Neat! I didn’t know about that. :smiley: