Wait for a keypress

Absolutely stupid question - and yes RTFM.
How do I make a Julia program pause until a key is pressed?

3 Likes
readline()

should do the trick? (maybe not the most elegant thing to do though…)

Thankyou

julia> wait_for_key(prompt) = (print(stdout, prompt); read(stdin, 1); nothing)
wait_for_key (generic function with 1 method)

julia> wait_for_key("press any key to continue")
press any key to continue
1 Like

The wait_for_key method only responds on enter for me, am I doing something wrong?

No, I think you need to work with a “raw” terminal. Perhaps

function wait_for_key(; prompt = "press any key", io = stdin)
    setraw!(raw) = ccall(:jl_tty_set_mode, Int32, (Ptr{Cvoid},Int32), io.handle, raw)
    print(io, prompt)
    setraw!(true)
    read(io, 1)
    setraw!(false)
    nothing
end

The REPL standard library has some functionality for this, but for terminals.

2 Likes

This thread is the top hit when searching for “julia wait for key” on google and the simple solution

julia> wait_for_key(prompt) = (print(stdout, prompt); read(stdin, 1); nothing)
wait_for_key (generic function with 1 method)

julia> wait_for_key("press any key to continue")
press any key to continue

is exactly what I needed, and for me it’s ok that Enter/Return is to be pressed.

But, perhaps it’s Windows, when used in a script (not REPL) after the first call stdin isn’t empty. Consecutive calls will not wait, because stdin still has something to read.

So an improvement, which works for me even for consecutive calls, would be:

wait_for_key(prompt) = (println(stdout, prompt);
	read(stdin, 1); 
	while bytesavailable(stdin)>0 read(stdin, Char); end; 
	nothing)

which reads all still available bytes from stdin until it’s really empty.