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
2 Likes

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.

4 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.

1 Like

If you are OK pressing Enter, but need to discard all (or most) of the characters, this might be simpler:

discard all

readline(stdin)

keep first character, even if it is Enter

c, _... = readline(stdin, keep=true)

1 Like

This SO solution from @bkamins is the only one that works for me in Windows.
NB: it is the same as @TamasPapp’s above, but without typo.

1 Like

Can anyone write a single julia function called press_any_key_to_continue()

such that

  1. Does NOT require user to press ENTER/RETURN button
  2. Works on Unix,Windows and Mac
  3. (hopefully) put it in a package that user can use easily. (; like “use easypackage” )

Regards…

All that is missing from your list is a package. Since the code is by @bkamins, it would be best if he put it in a mini-package, but if he does not want to I can package it up and register it with his permission.

2 Likes