Python 脚本在一段时间后停止运行 - raspberryPi 3

Python 脚本在一段时间后停止运行 - raspberryPi 3

我在我的 raspberry pi3 上使用 Ubuntu Mate,我正在尝试使用 python 建立客户端 - 服务器套接字连接,客户端脚本应该在 raspberry pi 每次启动时运行,并且该脚本也应该永远运行。

这是我的客户代码

import socket
import sys
import urllib.request
import time
import datetime

TCP_IP = sys.argv[1]
TCP_PORT = int(sys.argv[2])
BUFFER_SIZE = 1024
MESSAGE = "response"
flag = 0


def func():
    try:
        global flag
        flag = 1
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print("Socket Created")
        s.connect((TCP_IP, TCP_PORT))
        s.send(MESSAGE.encode())
        print("Sent 'response' message to server")
        while True:
            data = s.recv(BUFFER_SIZE)
            if not data:
                raise Exception('This is the exception you expect to handle')
            reply = data.decode().strip()
            print(reply)
            li = reply.split(",")
            if len(li) == 2:
                r = urllib.request.urlopen("http://127.0.0.1/sm.php?set=" + li[0] + "&device=" + li[1])
            else:
                s.send("received to client".encode())
    except Exception as e:
        now = datetime.datetime.now()
        stamp = now.strftime("%Y-%m-%d %H:%M:%S")
        with open("/home/mohit/ML/client_error.txt", "a") as myfile:
                    myfile.write(str(e) + " " + str(stamp)+"\n")
        print(str(e))
        time.sleep(10)
        s.close()
        s.detach()
        flag = 0
        return


while True:
    if flag == 0:
        func()

s.close()

为了在 Ubuntu 启动时启动脚本,我将其添加到 /etc/rc.local

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

python3 /home/mohit/ML/Server.py &
sleep 60
python3 /home/mohit/ML/ClientSocket.py xx.xx.xx.xx xxportxx &

exit 0

启动后,ClientSocket.py 文件运行一段时间,然后文件停止执行,出于测试目的,我在终端中手动运行了 ClientSocket.py 文件,文件在这种情况下正确执行。我无法理解为什么 python 文件会自行停止执行。

相关内容