PCM_Report/run_temperature_table.py

146 lines
4.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""
运行temperature_table.py的辅助脚本
自动设置正确的环境变量并运行脚本
"""
import os
import json
import subprocess
import sys
from datetime import datetime, timezone, timedelta
def load_influx_config():
"""从default.json加载InfluxDB配置"""
config_path = os.path.join(os.path.dirname(__file__), "default.json")
try:
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
return config.get('influx', {})
except Exception as e:
print(f"加载配置文件失败: {e}")
return {}
def convert_local_to_utc(local_time_str):
"""将本地时间转换为UTC时间
Args:
local_time_str: 本地时间字符串,格式如 "2025-11-27T11:30:00"
Returns:
UTC时间字符串格式如 "2025-11-27T03:30:00Z"
"""
try:
# 解析本地时间假设是UTC+8
local_dt = datetime.fromisoformat(local_time_str)
# 添加UTC+8时区信息
local_dt = local_dt.replace(tzinfo=timezone(timedelta(hours=8)))
# 转换为UTC
utc_dt = local_dt.astimezone(timezone.utc)
# 格式化为ISO字符串
return utc_dt.strftime('%Y-%m-%dT%H:%M:%SZ')
except Exception as e:
print(f"时间转换失败: {e}")
return local_time_str
def run_temperature_table(start_time, end_time):
"""运行temperature_table.py脚本
Args:
start_time: 实验开始时间(本地时间),如 "2025-11-27T11:30:00"
end_time: 实验结束时间(本地时间),如 "2025-11-27T12:00:00"
"""
print("运行 temperature_table.py 脚本")
print("=" * 50)
# 加载InfluxDB配置
influx_config = load_influx_config()
if not influx_config:
print("错误: 无法加载InfluxDB配置")
return False
# 转换时间为UTC
utc_start = convert_local_to_utc(start_time)
utc_end = convert_local_to_utc(end_time)
print(f"本地时间: {start_time}{end_time}")
print(f"UTC时间: {utc_start}{utc_end}")
print()
# 设置环境变量
env = os.environ.copy()
env.update({
'INFLUX_URL': influx_config.get('url', ''),
'INFLUX_ORG': influx_config.get('org', ''),
'INFLUX_TOKEN': influx_config.get('token', ''),
'INFLUX_BUCKET': influx_config.get('bucket', 'PCM'),
'INFLUX_MEASUREMENT': influx_config.get('measurement', 'PCM_Measurement'),
'EXPERIMENT_START': utc_start,
'EXPERIMENT_END': utc_end,
'TABLE_LOG_LEVEL': 'DEBUG',
'TABLE_LOG_FILE': 'temperature_table.log'
})
print("环境变量设置:")
for key in ['INFLUX_URL', 'INFLUX_ORG', 'INFLUX_BUCKET', 'INFLUX_MEASUREMENT', 'EXPERIMENT_START', 'EXPERIMENT_END']:
value = env[key]
if key == 'INFLUX_TOKEN':
value = value[:8] + '****' if len(value) > 8 else '****'
print(f" {key}: {value}")
print()
# 运行脚本
script_path = os.path.join(os.path.dirname(__file__), "temperature_table.py")
try:
print("正在运行脚本...")
result = subprocess.run(
[sys.executable, script_path],
env=env,
capture_output=True,
text=True,
timeout=60
)
print(f"返回码: {result.returncode}")
if result.stdout:
print("\n脚本输出:")
print(result.stdout)
if result.stderr:
print("\n错误输出:")
print(result.stderr)
# 显示日志文件最后几行
log_file = "temperature_table.log"
if os.path.exists(log_file):
print(f"\n日志文件最后10行:")
with open(log_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines[-10:]:
print(f" {line.strip()}")
return result.returncode == 0
except subprocess.TimeoutExpired:
print("错误: 脚本运行超时")
return False
except Exception as e:
print(f"错误: 运行脚本失败: {e}")
return False
def main():
if len(sys.argv) != 3:
print("用法: python run_temperature_table.py <开始时间> <结束时间>")
print("示例: python run_temperature_table.py 2025-11-27T11:30:00 2025-11-27T12:00:00")
return 1
start_time = sys.argv[1]
end_time = sys.argv[2]
success = run_temperature_table(start_time, end_time)
return 0 if success else 1
if __name__ == "__main__":
sys.exit(main())