我正在制作一个Python脚本,在EXT文件系统的情况下,它将创建一些东西的符号链接,否则它将移动文件。
如何知道目录的文件系统类型?
使用@Joachim Isaksson的建议的一些显式代码:
import os
try:
os.symlink("src", "dest")
except OSError:
print "cant do it :("
您可能应该做的就是尝试建立链接,如果失败,则复制。
它会给您带来的优势是,您将自动支持所有具有软链接的文件系统,而无需进行高级检测或保留支持的文件系统的更新列表。
已接受答案的一个变体,检查特定目录是否位于支持符号链接的文件系统上(并处理自身清理):
import os, pathlib, tempfile
def supports_symlinks(target_dir) -> bool:
with tempfile.TemporaryDirectory(dir=target_dir) as link_check_dir:
link_check_path = pathlib.Path(link_check_dir)
link_path = link_check_path / "src"
try:
os.symlink(link_path, "dest")
except OSError:
# Failed to create symlink under the target path
return False
# Successfully created a symlink under the target path
return True
在
symlink
上设置
shutil.copytree
选项时,这最有用,而不是在创建单个特定符号链接时。