我希望根据文件是否已经存在而写入文件,只有在文件尚不存在时才写入(实际上,我希望继续尝试文件,直到找到不存在的文件).
以下代码显示了潜在攻击者可以插入符号链接的方式,如本文所述,在文件测试和正在写入的文件之间.如果代码以足够高的权限运行,则可能会覆盖任意文件.
有什么方法可以解决这个问题吗?
import os
import errno
file_to_be_attacked = 'important_file'
with open(file_to_be_attacked, 'w') as f:
f.write('Some important content!\n')
test_file = 'testfile'
try:
with open(test_file) as f: pass
except IOError, e:
# symlink created here
os.symlink(file_to_be_attacked, test_file)
if e.errno != errno.ENOENT:
raise
else:
with open(test_file, 'w') as f:
f.write('Hello, kthxbye!\n')
Run Code Online (Sandbox Code Playgroud) 我正在编写一个程序,通过pickle模块缓存一些结果.此刻发生的情况是,如果我在dump
操作发生时按下ctrl-c,则会dump
中断并且生成的文件已损坏(即只是部分写入,因此无法load
再次编辑.
有没有办法制作dump
,或者通常是一段代码,不间断?我目前的解决方法看起来像这样:
try:
file = open(path, 'w')
dump(obj, file)
file.close()
except KeyboardInterrupt:
file.close()
file.open(path,'w')
dump(obj, file)
file.close()
raise
Run Code Online (Sandbox Code Playgroud)
如果它被中断,重启操作似乎很愚蠢,所以我正在寻找一种推迟中断的方法.我该怎么做呢?
rename(tmppath, path)
没有先拨打电话是否安全fsync(tmppath_fd)
?
我希望路径始终指向一个完整的文件.我主要关心的是Ext4.在所有未来的Linux内核版本中,rename()承诺是否安全?
Python中的一个用法示例:
def store_atomically(path, data):
tmppath = path + ".tmp"
output = open(tmppath, "wb")
output.write(data)
output.flush()
os.fsync(output.fileno()) # The needed fsync().
output.close()
os.rename(tmppath, path)
Run Code Online (Sandbox Code Playgroud) 我有一个长时间运行的进程,它在文件中写了很多东西.结果应该是一切或什么都没有,所以我写一个临时文件并在最后将其重命名为真实姓名.目前,我的代码是这样的:
filename = 'whatever'
tmpname = 'whatever' + str(time.time())
with open(tmpname, 'wb') as fp:
fp.write(stuff)
fp.write(more stuff)
if os.path.exists(filename):
os.unlink(filename)
os.rename(tmpname, filename)
Run Code Online (Sandbox Code Playgroud)
由于以下几个原因,我对此并不满意:
有什么建议如何改进我的代码?有没有可以帮助我的图书馆?
嗨,我正在尝试编写一个原子写入函数,如下所示......
with tempfile.NamedTemporaryFile(mode= "w", dir= target_directory) as f:
#perform file writing operation
os.replace(f.name, target_file_name)
Run Code Online (Sandbox Code Playgroud)
我正在努力找出第 3 行中最好的操作是什么。我应该使用 os.replace()、os.rename() 还是应该使用 os.link() 在临时文件和目标文件之间创建硬链接?
os.link() 使用更多内存吗?它们各自有什么好处?它们都是原子的吗?
在Python中以原子方式替换文件的推荐方法是什么?
即如果Python脚本被中断,则会出现断电等文件,并且很可能最终处于不一致状态(一半写入磁盘).
Linux/UNIX平台的解决方案是首选.
(我知道获得100%原子操作可能取决于您的文件系统,但至少使腐败的可能性降低)
在创建和写入之后,我尝试使用Popen()捕获文件.它不起作用.Print p给出两个空元组('','').为什么?我用的重命名,以确保原子写入,为讨论在这里.
#!/usr/bin/env python
import sys,os,subprocess
def run(cmd):
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
if p.returncode:
print "failed with code: %s" % str(p.returncode)
return p.communicate()
except OSError:
print "OSError"
def main(argv):
t = "alice in wonderland"
fd = open("__q", "w"); fd.write(t); fd.close; os.rename("__q","_q")
p = run(["cat", "_q"])
print p
main(sys.argv)
Run Code Online (Sandbox Code Playgroud)