Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

PythonでTCP/IPなsocket通信

昔ながらのsocket通信に出くわしたので試しにPythonで組んでみました。

実際のところ

送信側

import socket
import time

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
     s.connect(('127.0.0.1',9999))
     s.sendall(b"hello")

time.sleep(2)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
     s.connect(('127.0.0.1',9999))
     s.sendall(b"bye")

受信側

#!/usr/bin/env python3

import os
import sys

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(('127.0.0.1', 9999))
s.settimeout(None)
s.listen(1)

while True:
  conn, addr = s.accept()
  while True:
    data = conn.recv(1024)
    if not data:
        break
    print('data : {}'.format(data))
    if (data == b"hello"):
      print("hello done")
      break
    if (data == b"bye"):
      print("bye done")
      break
  conn.close()
s.close()

やってみると

$ python3 socktest.py
data : b'hello'
hello done
data : b'bye'
bye done

pythonの正規表現まわり

しょっちゅう忘れて全く記憶に残らないのでメモ

実際のところ

X=300だとかy=99みたいな感じで文字列が入ってくる際、左辺と右辺をそれぞれパースしたい場合は以下のように

import re

pt = re.compile(r'(x|y)=(\d{1,5})')
mt = pt.match("x=100")

mt[1]
#>> 'x'
mt[2]
#>> '100'

mt = pt.match("y=200")

mt[1]
#>> 'y'
mt[2]
#>> '200'

参考もと

docs.python.org

numpy-stlでSTLファイルを生成する その2:自分で平面ポリゴンをかく

実際のところ

import numpy as np
from stl import mesh

## 基準となる頂点を設定
vertices = np.array([\
    [-2, -1, +1],
    [-1, -1, +1],
    [ 0, -1, +1],
    [+1, -1, +1],
    [+2, -1, +1],
    [ 0,  0, +1]])

## 頂点を三点指定して三角形をつくる
faces = np.array([\
    [0,1,5],
    [3,4,5]])

# ポリゴンを生成
cube = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
for i, f in enumerate(faces):
    for j in range(3):
        cube.vectors[i][j] = vertices[f[j],:]

# STLファイルを生成
cube.save('cube.stl')

確認すると、こんな感じ
f:id:shuzo_kino:20220112211028p:plain

numpy-stlでSTLファイルを生成する その1:環境構築と動作確認

実際のところ

インストール

$ pip install numpy-stl

スクリプト

import numpy as np
from stl import mesh

# Define the 8 vertices of the cube
vertices = np.array([\
    [-1, -1, -1],
    [+1, -1, -1],
    [+1, +1, -1],
    [-1, +1, -1],
    [-1, -1, +1],
    [+1, -1, +1],
    [+1, +1, +1],
    [-1, +1, +1]])
# Define the 12 triangles composing the cube
faces = np.array([\
    [0,3,1],
    [1,3,2],
    [0,4,7],
    [0,7,3],
    [4,5,6],
    [4,6,7],
    [5,1,2],
    [5,2,6],
    [2,3,6],
    [3,7,6],
    [0,1,5],
    [0,5,4]])

# Create the mesh
cube = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))
for i, f in enumerate(faces):
    for j in range(3):
        cube.vectors[i][j] = vertices[f[j],:]

# Write the mesh to file "cube.stl"
cube.save('cube.stl')

f:id:shuzo_kino:20220111235549p:plain