Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 生成临时文件以替换实际文件_Python 3.x_Atomic_Temporary Files - Fatal编程技术网

Python 3.x 生成临时文件以替换实际文件

Python 3.x 生成临时文件以替换实际文件,python-3.x,atomic,temporary-files,Python 3.x,Atomic,Temporary Files,我需要生成一个临时文件,用新内容替换系统文件 我有代码,它可以工作,但我在想,是否有某个模块可以自动做到这一点,大致如下: with tempfile.NamedTemporaryFileFor('/etc/systemfile', delete=False) as fp: ... 这将在同一文件夹中创建一个具有与原始文件相同权限和所有者的临时文件。然后我将编写新内容,并用新的系统文件自动替换原来的系统文件。见鬼,当文件关闭时,上下文管理器可以替我做替换 我目前的代码是: with t

我需要生成一个临时文件,用新内容替换系统文件

我有代码,它可以工作,但我在想,是否有某个模块可以自动做到这一点,大致如下:

with tempfile.NamedTemporaryFileFor('/etc/systemfile', delete=False) as fp:
    ...
这将在同一文件夹中创建一个具有与原始文件相同权限和所有者的临时文件。然后我将编写新内容,并用新的系统文件自动替换原来的系统文件。见鬼,当文件关闭时,上下文管理器可以替我做替换

我目前的代码是:

with tempfile.NamedTemporaryFile(delete=False, dir='/etc') as fp:
    tempfilename = fp.name
    fp.write('my new contents')

orig_stat = os.stat('/etc/systemfile')
os.chown(tempfilename, orig_stat.st_uid, orig_stat.st_gid)
os.chmod(tempfilename, orig_stat.st_mode)

os.replace(tempfilename, '/etc/systemfile')

tempfile中没有这样的上下文管理器,但编写自己的上下文管理器并不太困难:

class NamedTemporaryFileFor(object):
    def __init__(self, orig_path, delete=True, dir=None):
        self.orig_path = orig_path
        self.named_temp_file = tempfile.NamedTemporaryFile(delete=delete, dir=dir)

    def __enter__(self):
        self.named_temp_file.__enter__()
        return self

    def write(self, *args, **kwargs):
        return self.named_temp_file.write(*args, **kwargs)

    def __exit__(self, exc, value, tb):
        orig_stat = os.stat(self.orig_path)
        os.chown(self.named_temp_file.name, orig_stat.st_uid, orig_stat.st_gid)
        os.chmod(self.named_temp_file.name, orig_stat.st_mode)

        self.named_temp_file.__exit__(exc, value, tb)

if __name__ == "__main__":
    with NamedTemporaryFileFor(sys.argv[1], delete=False, dir="/etc") as fp:
        f.write(b'my new content')
(请注意,我必须将一个字节字符串传递给
write
方法才能使示例正常工作)