Search code examples
juliatimeout

Julia: Run an external process for a given amount of time and capture its output


I want to run an external process in Julia for a given amount of time (say 10 seconds) and capture its output. I tried something like readchomp(`timeout 5 sleep 10`) (substitute sleep 10 by an arbitrary external process). However, a ProcessFailedException is thrown if the process was killed by timeout and I can not read the output of the program it produced until it was killed.


Solution

  • run only throws an exception if wait = true (which it is by default). You'll want to set that kwarg to false and then manually wait on the process, while redirecting stdout to e.g. an IOBuffer via pipeline:

    shell> cat loop.sh
    #!/bin/bash
    
    for i in {1..10}; do
        echo $i
        sleep 1
    done
    
    
    julia> b = IOBuffer()
    IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)
    
    julia> p = run(pipeline(`timeout 5 ./loop.sh`, stdout = b), wait = false); wait(p)
    
    julia> p
    Process(`timeout 5 ./loop.sh`, ProcessExited(124))
    
    julia> String(take!(b))
    "1\n2\n3\n4\n5\n"