文件元信息

更新时间:
复制 MD 格式

文件元信息用于查看文件或目录的名称、类型、路径、大小、权限、属主、修改时间和符号链接目标等信息。目录列表和重命名结果也会复用这类结构。

获取元信息

Python 示例:

sandbox.files.write("/tmp/demo/input.txt", "hello\n")

info = sandbox.files.get_info("/tmp/demo/input.txt")
print(info.name)
print(info.type)
print(info.path)
print(info.size)
print(info.permissions)

TypeScript 示例:

await sandbox.files.write("/tmp/demo/input.txt", "hello\n");

const info = await sandbox.files.getInfo("/tmp/demo/input.txt");
console.log(info.name);
console.log(info.type);
console.log(info.path);
console.log(info.size);
console.log(info.permissions);

其他字段

除上述字段外,EntryInfo 还包含属主、属组和修改时间等信息。

Python 示例:

info = sandbox.files.get_info("/tmp/demo/input.txt")
print(info.owner)
print(info.group)
print(info.modified_time)

TypeScript 示例:

const info = await sandbox.files.getInfo("/tmp/demo/input.txt");
console.log(info.owner);
console.log(info.group);
console.log(info.modifiedTime);

目录管理

Python 示例:

workdir = "/tmp/demo"

sandbox.files.make_dir(workdir)
sandbox.files.write(f"{workdir}/input.txt", "hello\n")

items = sandbox.files.list(workdir)
print(items)

sandbox.files.rename(f"{workdir}/input.txt", f"{workdir}/renamed.txt")
print(sandbox.files.exists(f"{workdir}/renamed.txt"))

sandbox.files.remove(workdir)

TypeScript 示例:

const workdir = "/tmp/demo";

await sandbox.files.makeDir(workdir);
await sandbox.files.write(`${workdir}/input.txt`, "hello\n");

const items = await sandbox.files.list(workdir);
console.log(items);

await sandbox.files.rename(`${workdir}/input.txt`, `${workdir}/renamed.txt`);
console.log(await sandbox.files.exists(`${workdir}/renamed.txt`));

await sandbox.files.remove(workdir);

文件状态

sandbox.files.exists(path) 可用于判断文件或目录是否存在,适合在执行命令前做前置检查。

Python 示例:

if not sandbox.files.exists("/tmp/demo/config.json"):
    sandbox.files.write("/tmp/demo/config.json", "{}\n")

TypeScript 示例:

if (!(await sandbox.files.exists("/tmp/demo/config.json"))) {
  await sandbox.files.write("/tmp/demo/config.json", "{}\n");
}

等待文件生成

需要等待目录内文件变化时,可以使用监听变化。如果只等待单个文件出现,也可以使用 sandbox.files.exists() 做有限次数轮询。

轮询时应设置超时和最大重试次数,避免任务长期占用资源。

自定义元数据

云沙箱当前不支持在写入文件时通过 metadata 附加自定义元数据。getInfo()list()rename() 返回的常规文件元信息不受影响。详情参见自定义元数据

使用建议

  • 业务代码应避免拼接未经校验的用户输入路径,防止越权访问工作目录外的文件。

  • 删除目录前,建议先确认路径前缀,避免误删系统目录或共享工作目录。

  • 需要长期保存的文件应写入外部存储,Sandbox 本地文件只适合当前任务生命周期内使用。