jinlx 发表于 2021-12-11 14:44:13

线程里的函数怎么引用不到实例化的属性?


下面的程序把 wincc.SetValue("ph",6.0)放在init()函数里不会报错,把它放在新开的线程message_handle(client, info)里就报错,说没这个属性。




import socket# 导入 socket 模块
from threading import Thread
import time
import json
import re

import win32com.client as win

ADDRESS = ('127.0.0.1', 1900)# 绑定地址

g_socket_server = None# 负责监听的socket

g_conn_pool = {}# 连接池


wincc = win.Dispatch(r'WinCC-Runtime-Project')

#wincc.SetValue("NewTag",value)
#wincc.GetValue("test2")

def init():
    """
    初始化服务端
    """
    global g_socket_server
    g_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    g_socket_server.bind(ADDRESS)
    g_socket_server.listen(5)# 最大等待数(有很多人理解为最大连接数,其实是错误的)
    print("server start,wait for client connecting...")

    #wincc.SetValue("ph",5.0)

def accept_client():
    """
    接收新连接
    """
    #wincc.SetValue("ph",5.0)   

    while True:
      client, info = g_socket_server.accept()# 阻塞,等待客户端连接
      # 给每个客户端创建一个独立的线程进行管理
      thread = Thread(target=message_handle, args=(client, info))
      # 设置成守护线程
      thread.setDaemon(True)
      thread.start()


def message_handle(client, info):
    """
    消息处理
   
    """
    wincc.SetValue("ph",5.0)

         
    #client.sendall("connect server successfully!".encode(encoding='utf8'))
    while True:
      try:
            bytes = client.recv(8192)
            msg = bytes.decode(encoding='utf8')
            
            if msg != '':
                print("1")

      except Exception as e:
            print(e)
            remove_client(client_type)
            break

def remove_client(client_type):
    client = g_conn_pool
    if None != client:
      client.close()
      g_conn_pool.pop(client_type)
      print("client offline: " + client_type)

if __name__ == '__main__':

    init()
    # 新开一个线程,用于接收新连接
    thread = Thread(target=accept_client)
    thread.setDaemon(True)
    thread.start()
    # 主线程逻辑
    while True:
      time.sleep(0.1)
      #print('33')
      #wincc.SetValue("ph",6.0)



上面的程序把 wincc.SetValue("ph",6.0)放在init()函数里不会报错,把它放在新开的线程message_handle(client, info)里就报错,说没这个属性。

错误是:Exception in thread Thread-4:
Traceback (most recent call last):
File "C:\Users\a\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
File "C:\Users\a\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
File "C:/python学习/test.py", line 53, in message_handle
    wincc.SetValue("ph",5.0)
File "C:\Users\a\AppData\Local\Programs\Python\Python38-32\lib\site-packages\win32com\client\dynamic.py", line 639, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: WinCC-Runtime-Project.SetValue

jinlx 发表于 2021-12-12 08:10:36

已解决。
页: [1]
查看完整版本: 线程里的函数怎么引用不到实例化的属性?