48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
# 工具函数
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import subprocess
|
||
|
||
from lib.core.VLogger import get_logger as _vlog
|
||
|
||
|
||
def DetectFileType(FilePath: str) -> str:
|
||
"""检测文件类型"""
|
||
_: str
|
||
ext: str
|
||
_, ext = os.path.splitext(FilePath)
|
||
return ext.lower()
|
||
|
||
|
||
def ExecuteCommand(command: list[str], shell: bool = False, CaptureOutput: bool = True, text: bool = True) -> subprocess.CompletedProcess[str] | None:
|
||
"""执行命令
|
||
command 应该是列表形式(如 ['gcc', 'file.c', '-o', 'file.exe'])
|
||
避免字符串拼接以防止 shell 注入"""
|
||
try:
|
||
result: subprocess.CompletedProcess[str] = subprocess.run(
|
||
command,
|
||
shell=shell,
|
||
check=True,
|
||
capture_output=CaptureOutput,
|
||
text=text
|
||
)
|
||
return result
|
||
except subprocess.CalledProcessError as e:
|
||
_vlog().error(f'编译失败: {e}')
|
||
if e.stderr:
|
||
_vlog().error(f'错误输出: {e.stderr}')
|
||
return None
|
||
|
||
|
||
def AppendFileContent(FilePath: str, content: str) -> bool:
|
||
"""追加文件内容"""
|
||
try:
|
||
with open(FilePath, 'a', encoding='utf-8') as f:
|
||
f.write(content)
|
||
f.write('\n')
|
||
return True
|
||
except Exception as e:
|
||
_vlog().error(f'写入文件失败 {FilePath}: {e}')
|
||
return False
|