'Python Script run in a tmux using ssh hangs in middle of execution

I have a requirement to perform some action every minute for 8 hours a day. I have a plan to start the python script using a cron job and then using datetime and sleep functions I try to achieve every minute execution and execution till some time.

I ssh to a remote linux vm, use tmux to open a session and then run the python script. Start time was 12:37 pm. Following is the code ::

import datetime
from time import sleep
print(datetime.datetime.now().time())
min = datetime.datetime.now().minute
i = 0
while(True):
    if (min == datetime.datetime.now().minute):
        i = i + 1
        print("conditions check " + str(i) + " timestamp :: " + str(datetime.datetime.now().time()) )
        print("conditions check end " + str(i) + " timestamp :: " + str(datetime.datetime.now().time()) )
        sleep(60 - datetime.datetime.now().second)
    elif(min < datetime.datetime.now().minute):
        min = datetime.datetime.now().minute
    if(datetime.datetime.now().time() > datetime.time(17,55,0)):
        print(datetime.datetime.now().time())
        break

This executed for i = 22 i.e 22 minutes and then it stopped working and got hanged.

I frequently experience not able to input text to terminal in tmux sessions.

output of ps aux | grep python

PID     %CPU    %MEM     VSZ       RSS   TTY      STAT        COMMAND
21495     85.9  0.5     123808    5364   pts/3    R+      python test1.py


Solution 1:[1]

First:

As @tripleee says, ensure your code runs at all

Second

When you say hanged it means that you are losing the connection to ssh? If so, you can start another terminal session enter in your remote using ssh, open tmux, and press ctrl+b+s to select with the arrows and enter your old session that was working, it will still be working.

There are another ways to attach directly for your session if you know the name of the session.

Option b

Call Python using the nohup command; for example:

nohup python3 main.py >> log.file &&

This will persist the task even if the connection is broken and store the prints/logs in a log file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1