python进程将赢得杀人方法的停止

发布于 2025-02-05 16:10:25 字数 3702 浏览 2 评论 0原文

因此,我正在尝试拥有一个自制的LED控制器(Raspberry Pi)。

控制器应该能够播放我自己预先定义的不同场景。 现在解决主要问题...

控制器以TCP服务器运行,并通过TCP消息改变他的场景。 我编码了很多场景,这些场景需要在循环时无休止地运行。 因此,如果新的TCP消息到达,我决定使用多处理能够杀死运行的“场景过程”。

因此,我的两个脚本的尴尬结果是,如果我在Windows上运行了服务器脚本,它的工作原理非常有效,但是如果IM更改以在Raspberry Pi上运行服务器脚本,则运行过程并不会像应有的那样被杀死。

因此,当我的服务器测试脚本时,我使用了以下内容:

import multiprocessing
import time

from time import sleep

try: 
    from analyse import *
    from handler import *
    from history import writeState
    from led import *
except: pass 

import socket


from subprocess import check_output #um die IP-Adresse unter Raspian auszulesen 
from platform import system


class SYSINFO():
    os=system() #Fragt das System nach dem laufenden OS-Typ ab

    if os=="Linux":
        IP_ADDRESS=check_output(["hostname",'-I']).decode().split(" ")[0]
    elif os=="Windows" or os=="Darwin":
        IP_ADDRESS=  socket.gethostbyname(socket.gethostname())#"192.168.168.97"


class MyProcess(multiprocessing.Process):

    def __init__(self, ):
        multiprocessing.Process.__init__(self)
        self.exit = multiprocessing.Event()

    def run(self):
        while not self.exit.is_set():
            print(round(time.perf_counter()), self.pid)
            time.sleep(1)
        print("You exited!")

    def shutdown(self):
        print("Shutdown initiated")
        self.exit.set()

class TCPController(multiprocessing.Process): 
    def __init__(self, ):
        multiprocessing.Process.__init__(self)
        self.exit = multiprocessing.Event()

    def run(self): 
        counter=0
        
    
    def shutdown(self):
        print("Shutdown initiated")
        self.exit.set()

if __name__ == "__main__":
    
    HOST = SYSINFO.IP_ADDRESS  # Standard loopback interface address (localhost
    PORT = 6060  # Port to listen on (non-privileged ports are > 1023)
    
    while True:

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind((HOST, PORT))
            print(f"server listens under  {HOST!r} ,  {PORT!r} now")

            s.listen()
        
            while True: 
                try:
                    conn, addr = s.accept()
                    print("waiting for connection")
                    with conn: 
                        print(f"Connected by {addr}")
                        data = conn.recv(1024).decode()
                        print(data)
                        if data=="on": 
                            process = MyProcess()
                            process.daemon=True
                            process.start()
                            time.sleep(3)
                        elif data=="off": 
                            #process.shutdown()
                            process.kill()
                            time.sleep(3)
                            print("Child process state: %d" % process.is_alive())
                except: pass
                sleep(.5)

我的客户端测试周期脚本看起来像是

# echo-client.py

import socket

from time import sleep

class heimkinoSteuereinheit: 
        
    HOST = "192.168.168.97" #"192.168.168.97"  # The server's hostname or IP address
    PORT = 6060  # The port used by the server


def cinemaclient(msg):

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((heimkinoSteuereinheit.HOST, heimkinoSteuereinheit.PORT))
        s.sendall(msg.encode())
        data = s.recv(1024).decode()
       
    print(f"Received {data!r}")
    return data

while True: 
  sleep(1)
  cinemaclient("on")
  sleep(5)
  cinemaclient("off")

希望你们能提供帮助。

感谢您的帮助, 卢卡

So I'm trying having a self-made led-controller (raspberry pi).

The Controller should be able to play different scenes which were pre-defined by myself.
Now to the main problem...

The controller runs as TCP server and gets his scene-changes by tcp messages.
i coded a lot of scenes which need to run in an endless while loop.
So I decided to use multiprocessing to be able killing the running "scene process" if a new tcp message arrives.

So the awkward result of my two scripts are that if I'm running the server script on windows its perfectly working, but if im changing to run the server script on raspberry pi the running process isn't getting killed like it should.

so as my server test script I used the following:

import multiprocessing
import time

from time import sleep

try: 
    from analyse import *
    from handler import *
    from history import writeState
    from led import *
except: pass 

import socket


from subprocess import check_output #um die IP-Adresse unter Raspian auszulesen 
from platform import system


class SYSINFO():
    os=system() #Fragt das System nach dem laufenden OS-Typ ab

    if os=="Linux":
        IP_ADDRESS=check_output(["hostname",'-I']).decode().split(" ")[0]
    elif os=="Windows" or os=="Darwin":
        IP_ADDRESS=  socket.gethostbyname(socket.gethostname())#"192.168.168.97"


class MyProcess(multiprocessing.Process):

    def __init__(self, ):
        multiprocessing.Process.__init__(self)
        self.exit = multiprocessing.Event()

    def run(self):
        while not self.exit.is_set():
            print(round(time.perf_counter()), self.pid)
            time.sleep(1)
        print("You exited!")

    def shutdown(self):
        print("Shutdown initiated")
        self.exit.set()

class TCPController(multiprocessing.Process): 
    def __init__(self, ):
        multiprocessing.Process.__init__(self)
        self.exit = multiprocessing.Event()

    def run(self): 
        counter=0
        
    
    def shutdown(self):
        print("Shutdown initiated")
        self.exit.set()

if __name__ == "__main__":
    
    HOST = SYSINFO.IP_ADDRESS  # Standard loopback interface address (localhost
    PORT = 6060  # Port to listen on (non-privileged ports are > 1023)
    
    while True:

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            s.bind((HOST, PORT))
            print(f"server listens under  {HOST!r} ,  {PORT!r} now")

            s.listen()
        
            while True: 
                try:
                    conn, addr = s.accept()
                    print("waiting for connection")
                    with conn: 
                        print(f"Connected by {addr}")
                        data = conn.recv(1024).decode()
                        print(data)
                        if data=="on": 
                            process = MyProcess()
                            process.daemon=True
                            process.start()
                            time.sleep(3)
                        elif data=="off": 
                            #process.shutdown()
                            process.kill()
                            time.sleep(3)
                            print("Child process state: %d" % process.is_alive())
                except: pass
                sleep(.5)

my client test cycle script looks like that

# echo-client.py

import socket

from time import sleep

class heimkinoSteuereinheit: 
        
    HOST = "192.168.168.97" #"192.168.168.97"  # The server's hostname or IP address
    PORT = 6060  # The port used by the server


def cinemaclient(msg):

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((heimkinoSteuereinheit.HOST, heimkinoSteuereinheit.PORT))
        s.sendall(msg.encode())
        data = s.recv(1024).decode()
       
    print(f"Received {data!r}")
    return data

while True: 
  sleep(1)
  cinemaclient("on")
  sleep(5)
  cinemaclient("off")

Hope you guys could help.

Thanks for your help,
Luca

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

呆萌少年 2025-02-12 16:10:25

可变过程仅在

if data=="on"

的变量过程的同时

if data=="off

您使用尚未定义 定义。那是故意完成的吗?

此外,您的代码是什么意思是不起作用的。你有任何错误吗?

The variable process is only defined in the

if data=="on"

While you use the variable process in the

if data=="off

It has not been defined. Is that done intentionally?

Furthermore what do you mean by the code isn't working. Do you get any errors?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文