I am writing a python script with an infinite while loop that I run on top of ssh. I would like the script to terminate when someone killed ssh. For instance:
script (script.py):
while True:
Will run as:
ssh foo ./script.py
When I kill the ssh process, I would like the script on the other end to stop working.
I tried looking for a closed scene:
while not sys.stdout.closed: # do something
but it didn’t work.
How do I achieve this?
Edit
A remote computer is a Mac that opens a program in csh:
502 29352 ?? 0:00.01 tcsh -c python test.py 502 29354 ?? 0:00.04 python test.py
I open the ssh process from a python script as follows:
p = Popen(['ssh','foo','./script.py'],stdout=PIPE) while True: line = p.stdout.readline() # etc
EDIT
Suggested solutions:
- Run the script with
while os.getppid() != 1
This is similar to working with Linux systems, but does not work when OSX is running on the remote computer. The problem is that the command runs in csh (see above), so csh has its parent process id set to 1, but not a script.
- Log in to
stderr periodically
This works, but the script also runs locally, and I don't want to print a heartbeat before stderr .
- Run the script in pseduo tty using
ssh -tt .
This works, but has some strange effects. Consider the following:
remote_script:
#!/usr/bin/env python import os import time import sys while True: print time.time() sys.stdout.flush() time.sleep(1)
local_script:
#!/usr/bin/env python from subprocess import Popen, PIPE import time p = Popen(['ssh','-tt',' user@foo ','remote_script'],stdout=PIPE) while True: line = p.stdout.readline().strip() if line: print line else: break time.sleep(10)
First of all, the conclusion is really strange, it seems that it adds tabs or something else:
[ user@local ~]$ local_script 1393608642.7 1393608643.71 1393608644.71 Connection to foo closed.
Secondly, the program does not exit the first time when it receives SIGINT , i.e. I need to press Ctrl-C twice to kill local_script.