2 篇文章带有标签 “tempfile”

使用 Python 临时文件模块

file.write() 内容超过 4K 才会写入磁盘

验证代码

import os
import tempfile

for count in range(1, 4100):
    content = '0'*count
    with tempfile.NamedTemporaryFile() as file:
        print(file.name)
        file.write(content.encode())

        with open(file.name, 'r') as tf:
            content_len = len(tf.read())
            if content_len > 0:
                print(f'{count} bytes written successfully.')

运行结果 /var/folders/bc/7lz308t90gb1h1xw6k4j65x80000gn/T/tmpj458ozas /var/folders/bc/7lz308t90gb1h1xw6k4j65x80000gn/T/tmpmrxo8sg1 /var/folders/bc/7lz308t90gb1h1xw6k4j65x80000gn/T/tmp0hu_i4hz 4097 bytes written successfully.

Docker SDK for Python Examples

安装 Docker SDK for Python

pip install docker

例子

将本地文件或目录添加到容器,生成新的镜像。

  • put_archive
  • commit
import docker
import tarfile
import tempfile
import os

def simple_tar(path):
    f = tempfile.NamedTemporaryFile()
    t = tarfile.open(mode='w', fileobj=f)
    abs_path = os.path.abspath(path)
    t.add(abs_path, arcname=os.path.basename(path))
    t.close()
    f.seek(0)
    return f

client = docker.from_env()
// ...

参考资料