websocket 在run函数内从另一个python文件导入python文件中的变量

ykejflvf  于 2023-01-17  发布在  Python
关注(0)|答案(1)|浏览(109)

我在python中有两个WebSocket处理程序文件一个是用来和flask webserver通信的,另一个是用来和工业机器人通信的,我需要在robot处理程序的run函数内部导入一个变量来在flask网页上显示它,但是每当我试图将robot处理程序的类和函数导入到flask处理程序时,pylance都显示“code is unreachable”。
培养瓶处理器

import threading
from threading import Thread
import logging
import asyncio
import socket
import websockets
import time
from handlers.kukahandler import *
import re

all_clients = []
current_coordinates = 50.29;
#updated_coordinates = 5,291,0,266803,-153,502404,-1800,0,1800,769350;

word = 'update value!'

coordinates = Kuka_tcphandler(handlername= None, run_event= None)
updated_coordinates = coordinates.run()

class client_handler(Thread):
    def __init__(self, handlername, run_event):
         # init process attrributes
        Thread.__init__(self, target=None, name=handlername)
        self.lock = threading.Lock()
        self.run_event = run_event
        logging.info("calling server connect ... ")

    def run(self):
        while self.run_event.is_set():
            socket = start_serverr()
            asyncio.run(socket.start_server())
        else:
            logging.error("Cannot run client handler, because it is not connected.")           

class start_serverr(object):
    print("hii")

    async def start_server(self):
        logging.info("server started")
        async with websockets.serve(self.new_client_connected, "localhost", 7999):
            await asyncio.Future()  # run forever
    
    async def new_client_connected(self, client_socket):
        logging.info("client connected called")
        print("New client connected!")
        all_clients.append(client_socket)
    
        while True:
            for client in all_clients:
                new_message = await client_socket.recv()
                print("client Sent:", new_message)
                #updated_coordinates = result[0]
                
                if new_message == 'update value!':
                    await client.send(str(updated_coordinates))
                    
                elif new_message == 'sendcoords':
                 await client.send(str(current_coordinates))

机器人处理器

import threading
import time
from threading import Thread
import logging
import socket
import sys
import re

class Kuka_tcphandler(Thread):
    '''
    TCP/IP handler for kuka
    '''
    def __init__(self, handlername, run_event):
        # init process attrributes
        Thread.__init__(self, target=None, name=handlername)
        self.lock = threading.Lock()
        self.run_event = run_event
        self.isconnected = False
        #self.coord = None
        # Initializing Connection
        self.init_tcp()

        # Connect to the endpoint
        self.connecttoendpoint()

    def init_tcp(self):
        '''
        Initializing TCP connection
        '''
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def connecttoendpoint(self):
        '''
        Establish the tcp/ip connection to the camera device
        '''
        self.serveraddress = ('localhost', int(8500))

        try:
            self.sock.connect(self.serveraddress)
            logging.info("Connected")
            self.isconnected = True
        except Exception as e:
            logging.ERROR("ERROR!: cannot connect :" + str(e))

    def run(self):
        while True:
            try:
                self.sock.send(b'CRBT,4,250,254')
                time.sleep(2)
                coord = self.sock.recv(128)
                logging.warning("coord:" + str(coord))
                print(type(coord))
        
            except Exception as e:
                logging.error("ERROR!: cannot request :" + str(e))

if __name__ == "__main__":
    # Init  run event
    run_event = threading.Event()
    # Set run event
    run_event.set()

我需要将robot处理程序的run函数中的变量“coord”导入到flask处理程序中。当我在run函数末尾返回该变量时,它工作正常,但它关闭了与robot的连接。

ocebsuys

ocebsuys1#

如果你想在机器人处理程序中得到 flask 处理程序的变量值,只需将其存储在文本文件中并再次读取即可
在培养瓶处理器中:

f=open('coord.txt','w')
f.write(coord)
f.close()

在机器人处理器中:

f=open('coord.txt','r')
coord=f.read()
f.close()

相关问题