File size: 1,539 Bytes
a783ac1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import subprocess
import re
def run_shortcuts_cli():
"""執行 macOS 捷徑並傳回輸出的文字"""
try:
result = subprocess.run(["shortcuts", "run", "GetMyLocation"], capture_output=True, text=True, timeout=10)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
except Exception:
pass
return None
def get_mac_gps():
"""主要定位入口,透過捷徑取得定位資訊,並在這邊進行列印與解析"""
output = run_shortcuts_cli()
if not output:
print("無法透過 macOS 捷徑取得定位資訊(請確認捷徑 \"GetMyLocation\" 是否存在)。")
return None
# 在此處列印捷徑回傳的原始文字
print("\n[macOS 捷徑輸出]:")
print(output)
# 嘗試解析經緯度
numbers = re.findall(r'[-+]?\d+\.\d+', output)
if len(numbers) >= 2:
try:
lat = float(numbers[0])
lon = float(numbers[1])
if -90 <= lat <= 90 and -180 <= lon <= 180:
# 台灣經緯度合理範圍調整(若經度在前面則對調)
if 100 <= lat <= 130 and 10 <= lon <= 40:
lat, lon = lon, lat
print("\n[成功解析經緯度]")
print(f"緯度 (Latitude) : {lat}")
print(f"經度 (Longitude): {lon}")
return {"lat": lat, "lon": lon}
except ValueError:
pass
return output
if __name__ == "__main__":
get_mac_gps()
|