Readline with default value if no input after timeout

I am to write a code that asks for a prompt from the REPL but defaults to some predefined string if the user does not input anything within e.g. 10 seconds.

I was thinking of using readline but I can’t seem to find a way to make it stop if no input is given after a certain period.

How would one achieve this?

Probably not the most elegant solution, but it works:

msg = Channel{String}(1)

task = Task() do
    try
        eof(stdin)
        put!(msg, readline(stdin))
    catch
        put!(msg, "no input received!")
    end
end

interrupter = Task() do
    sleep(1)
    if !istaskdone(task)
        Base.throwto(task, InterruptException())
    end
end

schedule(interrupter)
schedule(task)
println("waiting ..")
wait(task)
println(take!(msg))
1 Like