当前位置:网站首页>Ansa secondary development - external programs use socket to communicate with ansa

Ansa secondary development - external programs use socket to communicate with ansa

2022-06-21 07:34:00 CaeCoder

The implementation steps are as follows

  1. stay ANSA Script Edit Running server code in :
#  Server code socket_server.py
 
import socket
import os
import sys
 
def work():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',1000))
    sock.listen(1)
    while True:
        try:
            conn, addr = sock.accept()
            ret = conn.recv(2048)
            # result = os.popen(ret).read()
            # popen(ret) Wrong command 
            result = exec(ret)
            conn.send("success".encode())
        except KeyboardInterrupt:
            print('Now we will exit')
            sys.exit(0)
    sock.close()

if __name__ == '__main__':
    work()
 Click on 【 function 】 Button :

 Insert picture description here
After operation ANSA The main program is locked :
 Insert picture description here
2. Client code client.py

#  Client code client.py
import socket
 
def socket_send(command):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('localhost', 1000))
    sock.send(command)
    result = sock.recv(2048)
    sock.close()
    return result
 
cmd = '''from ansa import base from ansa import constants fields = {'X1': 3.5, 'X2': 10.8, 'X3': 246.7} new_grid = base.CreateEntity(constants.NASTRAN, 'GRID', fields) print('The id of the new grid:', new_grid._id) '''
print(socket_send(cmd.encode()))
  1. open Python IDLE( need python3 The compiler ), as follows File —>Open open client.py
     Insert picture description here
    function Run:Run Module or F5 function
     Insert picture description here

  2. see ANSA Operation in : You can see that the node has been created ( Only the main process is closed socket after ANSA To operate , Created Grid Only then )
     Insert picture description here

add to WX official account - CAE Second development of software Lab, See more great technical articles !

There are problems :

 At present only in ANSA Run in the main thread socket, But running socket after ANSA The main thread is locked , Lead to ANSA Can't operate ; Only the main process is closed socket after ANSA To operate , Created ANSA Object appears .
原网站

版权声明
本文为[CaeCoder]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210733510913.html