ข้ามไปยังเนื้อหา

บทที่ 3 Project Setup

สร้างโปรเจกต์ใหม่

Step 1: สร้างโฟลเดอร์โปรเจกต์

Terminal window
mkdir MyEtabsApp
cd MyEtabsApp

Step 2: สร้าง Virtual Environment

Terminal window
python -m venv .venv

เปิดใช้งาน:

Terminal window
# Windows PowerShell
.venv\Scripts\Activate.ps1
# Windows CMD
.venv\Scripts\activate.bat

Step 3: ติดตั้ง Dependencies

Terminal window
pip install comtypes pandas openpyxl

Step 4: สร้าง requirements.txt

Terminal window
pip freeze > requirements.txt

หรือสร้างเองแบบ minimal:

comtypes>=1.4.0
pandas>=2.0.0
openpyxl>=3.1.0

ProgID ที่ถูกต้อง

ProgID เป็น string ที่ Windows ใช้ค้นหา COM object ที่ลงทะเบียนไว้:

CSI.ETABS.API.ETABSObject

ProgID นี้ ใช้เหมือนกันทุก version ของ ETABS (17-21+) ระบบจะเชื่อมกับ ETABS instance ที่เปิดอยู่ (ตัวล่าสุด)

Minimal Script (พร้อมรัน)

นี่คือโค้ดเริ่มต้นที่เล็กที่สุดที่ทำงานได้ — สร้างไฟล์ main.py:

"""
Minimal ETABS API Script
ต้องเปิด ETABS และเปิดโมเดลก่อนรัน
"""
import comtypes.client
import gc
etabs = None
sap_model = None
try:
# 1. เชื่อม ETABS ที่เปิดอยู่
etabs = comtypes.client.GetActiveObject("CSI.ETABS.API.ETABSObject")
if etabs is None:
print("❌ ไม่สามารถเชื่อม ETABS ได้ — ตรวจสอบว่าเปิด ETABS อยู่")
exit(1)
# 2. เข้าถึง SapModel
sap_model = etabs.SapModel
if sap_model is None:
print("❌ ไม่สามารถเข้าถึง SapModel ได้ — ตรวจสอบว่าเปิดโมเดลแล้ว")
exit(1)
print("✅ เชื่อม ETABS สำเร็จ!")
# 3. อ่านชื่อไฟล์โมเดล
model_path = sap_model.GetModelFilename()
print(f"📁 ไฟล์โมเดล: {model_path}")
except OSError as e:
print(f"❌ COM Error: {e}")
except Exception as e:
print(f"❌ Error: {e}")
finally:
# 4. Cleanup COM objects
if sap_model is not None:
del sap_model
if etabs is not None:
del etabs
gc.collect()
print("\n🧹 Cleanup เสร็จ")

Expected Output (เมื่อเปิด ETABS และเปิดโมเดลอยู่)

✅ เชื่อม ETABS สำเร็จ!
📁 ไฟล์โมเดล: C:\Models\MyBuilding.EDB
🧹 Cleanup เสร็จ

วิธีรัน

Terminal window
python main.py

โครงสร้างไฟล์โปรเจกต์

หลังจาก setup เสร็จ โปรเจกต์จะมีหน้าตาแบบนี้:

MyEtabsApp/
├── .venv/ ← virtual environment
├── main.py ← โค้ดหลัก
├── requirements.txt ← dependencies
└── .gitignore

.gitignore สำหรับ Python + ETABS

# Python
.venv/
__pycache__/
*.pyc
*.pyo
.pytest_cache/
# IDE
.vscode/
.idea/
# Output
output/
*.csv
*.xlsx
logs/
# OS
.DS_Store
Thumbs.db

ความแตกต่างกับ C#

หัวข้อC#Python
IDEVisual Studio (2019/2022)VS Code / PyCharm
Platformต้องตั้ง x64 เองไม่ต้อง — Python auto-detect
DLL Referenceต้อง add CSiAPIv1.dllไม่ต้อง — comtypes เรียก COM ตรง
Buildต้อง compile ก่อนรันไม่ต้อง — รัน script ได้เลย
Type Safetycompile-time checkruntime (dynamic typing)

Checklist ก่อนไปบทถัดไป

  • สร้างโฟลเดอร์โปรเจกต์ + venv แล้ว
  • ติดตั้ง comtypes, pandas แล้ว
  • สร้าง requirements.txt แล้ว
  • สร้าง main.py (minimal script) แล้ว
  • รัน python main.py ได้ (ต้องเปิด ETABS ก่อน)