Is there a macro to make Ctrl+C work in REPL?

This topic shows that Julia REPL can not be interrupted : How to interrupt (not kill) julia from the REPL?

Is there a decorator to make a loop able to be interrupted from Ctrl+C in the REPL?

Julia does not have python-style decorators - perhaps you’re thinking of a macro?

In any case, you can try to write your loop like

for x in y
    try
       # loop body
    catch e 
       e isa InterruptException && break
       rethrow(e) # so we don't swallow true exceptions
    end
end

But be aware that this is not a surefire way of achieving this (and I’m fairly certain it’s not guaranteed to work, depending on the loop body). For example, the interrupt can happen at any point in time, so also when the iterator state is advanced (which is not covered by this) or in another task (should there be another task running at the same time, either spawned before this loop runs or spawned in the loop itself).

2 Likes

Yes, sorry for the name, I was thinking about a macro.

Doing

while true
    try
        # nothing in the loop
    catch e
        # in any case
        break
    end
end

does not allow to interrupt with Ctrl+C.

How can we achieve this and put this in a macro so that we can write

@allow_interrupt while true
    # nothing
end

And interrupt the loop with Ctrl+C?

Calling yield() from within the loop is the generally recommended option for this. It’s not a 100% guarantee as I understand it, but makes it much more likely that the interrupt comes through. See for eg.

1 Like

That seems to be a bug - you can force throw a SIGINT by repeatedly pressing Ctrl+C.

Regardless, it’s not reliable as it can happen at any time - it’s usually preferable to have an explicit synchronization point where an external signal is checked for being set or not.

1 Like

Take a look at the docs here

Haven’t tried it, but looks promising.

1 Like

disable_sigint takes a function, I have no idea what to give it so that I can Ctrl-C a while loop.