0

I'm using a simple python.py script in Linux. I need to run a while/counter loop and would like to stop the loop immediately by using a/any terminal command. I need to run the script using Screen. Simply stopping the Screen session doesn't work - it only stops the current process in the loop and then continues with the next process. The terminal command must preferably be specific for the loop in question.

I was looking at a Try / Except loop:

x = 1
y = 100
try:
    while x < y:
        process x
        time.sleep(10)
        x = x + 1
except ?

I don't know where to start. I need help with the implementation or maybe a better way to do this.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Something like [this](http://stackoverflow.com/questions/13180941/how-to-kill-a-while-loop-with-a-keystroke)? – Murillio4 Oct 02 '16 at 21:40
  • Almost. I get the idea with the Keyboard Interrupt, but the script is actually triggered from php through ssh2_exec. I was hoping to be able to use exec or ssh2_exec to terminate the script/loop as well. – Renier Delport Oct 02 '16 at 21:54
  • Is it possible to inserting a letter instead? – Murillio4 Oct 03 '16 at 06:11
  • @Murillio4 Did some reading up. I trigger the puthon.py through a Screen command to run in the background. With screen I have the ability to insert a letter yes (through 'stuff'). I don't know if it is going to work though. What do you have in mind? – Renier Delport Oct 03 '16 at 06:54
  • If it's possible o break the loop with user input, that would be the easiest solution. https://ubuntuforums.org/showthread.php?t=1514035 – Murillio4 Oct 03 '16 at 08:57
  • @Murillio4 I've been trying to overcome this problem for ages. Your help made me think a bit and I managed to bypass the try/except loop by just adding an 'and condition' to the while loop. I then kill process x and change the 'and condition' with a little Bash script (which can be accessed through the terminal. Thank you for your help. – Renier Delport Oct 03 '16 at 11:44

1 Answers1

0

If this is linux then you can use Operating System Signals. Just create a signal handler that throws an exception and catch that exception. Register the signal handler with

signal.signal(signal.SIGINT, handler)

This will register the handler function to be called when ever the SIGINT is sent to the process ID.

import signal, time
class InterruptException(Exception):
    pass

def handler(signum, frame):
    raise InterruptException("Recieved SIGINT")


# Set the signal handler
signal.signal(signal.SIGINT, handler)

x = 1
y = 100
try:
    while x < y:
        print x
        time.sleep(10)
        x = x + 1
except InterruptException:
    print "Iterrupted"

From bash you can use

kill -2 PID

where PID is the process ID for the running script

You could always launch and kill from bash like

python my.app &
MY_PID=$!
kill -2 $MY_ID
Simon Black
  • 913
  • 8
  • 20