簡體   English   中英

Python中遞歸遍歷多個符號鏈接

[英]Traversing multiple symbolic links recursively in Python

我想寫一個遞歸 function 來遍歷從源路徑到目標路徑的符號鏈接

示例:1)readlink patha/pathb/pathc -> 如果符號鏈接存在則給出 2)readlink patha/pathb/pathc/ -> 如果符號鏈接存在則給出

我在 python 中使用 os.readlink 方法來獲取 Python 中的符號鏈接,但是如何遍歷多個符號鏈接

遍歷的原因:如果將來有人想在兩者之間添加 file3 符號鏈接,那么我想要一個遞歸 function 來遍歷每個符號鏈接並給出最終的 dest 路徑
file1 -> file2 ->.... -> 用於獲取目標路徑

你可以簡單地使用

import os

def find_link(path):
   try:
        link = os.readlink(path)
        return find_link(link)
   except OSError: # if the last is not symbolic file will throw OSError
        return path

print(find_link("a/b/c"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM