Python3follow_symlinks
在Python 3中,shutil的大多数复制方法都学习了follow_symlinks参数,如果选择了该参数,它将保留符号链接。
例如,对于shutil.copy:shutil.copy(src, dest, follow_symlinks=False)shutil.copy(src, dst, *, follow_symlinks=True)
Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.
If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks` is true and src is a symbolic link, dst will be a copy of the file src refers to.
但是,这有一个问题:如果试图覆盖现有文件或符号链接,它将失败:FileExistsError: [Errno 17] File exists: 'b' -> 'c'
与成功覆盖的follow_symlinks=True不同。
同样的情况也发生在os.symlink上,因此我最终使用了:#!/usr/bin/env python3
import shutil
import os
def copy(src, dst):
if os.path.islink(src):
if os.path.lexists(dst):
os.unlink(dst)
linkto = os.readlink(src)
os.symlink(linkto, dst)
else:
shutil.copy(src, dst)
if __name__ == '__main__':
os.symlink('c', 'b')
os.symlink('b', 'a')
copy('a', 'b')
with open('c', 'w') as f:
f.write('a')
with open('d', 'w'):
pass
copy('c', 'd')
copy('a', 'c')
在Ubuntu 18.10,Python 3.6.7中测试。