[PYTHON] Convert a path string that uses a symbolic link in the middle to an absolute path

A script that makes an absolute path when a directory is specified with a symbolic link in the middle of the path.

code

followlnk.py


#!/usr/bin/env python
import os
import sys
import os.path

def follow_link(path):
    path = os.path.abspath(path)
    path_fragments = []
    current = ""
    while True:
        path, child = os.path.split(path)
        if child == '':
            current = path # /
            break
        path_fragments.insert(0, child)
    while path_fragments:
        current = follow_child(current, path_fragments[0])
        path_fragments = path_fragments[1:]
    print(current)

def follow_child(current, child):
    result = os.path.join(current, child)
    if not os.path.islink(result):
        return result 
    link = os.readlink(result)
    if os.path.isabs(link):
        return link
    return os.path.abspath(os.path.join(current, link))

if __name__ == "__main__":
    if len(sys.argv) > 1:
        follow_link(sys.argv[1])
    else:
        print("%s [directory]" % sys.argv[0])
        sys.exit(1)

It's a discarded script, so it's appropriate, but all you have to do is break down the path first and then go down the directory, checking for symlinks in order from the top. Since I haven't checked for errors, I may die if a directory that doesn't exist appears on the way.

How to use

$ followlink.py ./test/symdir/subdir  #symdir is a symbolic link to realdir in the same location
/Users/home/shibukawa/develop/test/realdir/subdir

Recommended Posts

Convert a path string that uses a symbolic link in the middle to an absolute path
Convert a string to an image
The eval () function that calculates a string as an expression in python
How to convert / restore a string with [] in python
A string permutation code that uses an algorithm that generates permutations.
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
How to put a symbolic link
How to make a string into an array or an array into a string in Python
[Ln] How to paste a symbolic link in a directory is complicated
Get the formula in an excel file as a string in Python
Note: [Python3] Convert datetime to a string in any format you like
It was dangerous to specify a relative path when generating a symbolic link
I want to batch convert the result of "string" .split () in Python
View the full path (absolute path) of a file in a directory in Linux Bash
I want to color a part of an Excel string in Python
Use BeautifulSoup to extract a link containing a string from an HTML file
Convert absolute URLs to relative URLs in Python
I want to create an API that returns a model with a recursive relationship in the Django REST Framework
A solution to the problem that the Python version in Conda cannot be changed
To output a value even in the middle of a cell with Jupyter Notebook
I made an appdo command to execute a command in the context of the app
Create a filter to get an Access Token in the Graph API (Flask)
What do you like about how to convert an array (list) to a string?
How to embed a variable in a python string
Insert an object inside a string in Python
A story that failed when trying to remove the suffix from the string with rstrip
[Ansible] Example of playbook that adds a character string to the first line of the file
[Python] Leave only the elements that start with a specific character string in the array
A story that an error occurred when PyInstaller was used in a program that uses googleapiclient
A note that runs an external program in Python and parses the resulting line
A story about trying to introduce Linter in the middle of a Python (Flask) project
A solution to the problem that files containing [and] are not listed in glob.glob ()
How to find the first element that matches your criteria in a Python list
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
Check if the string is a number in python
Parse a JSON string written to a file in Python
I want to embed a variable in a Python string
[Python] How to expand variables in a character string
# Function that returns the character code of a string
Convert the image in .zip to PDF with Python
[Python] Created a method to convert radix in 1 second
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
When reading an image with SimpleITK, there is a problem if there is Japanese in the path
How to quickly count the frequency of appearance of characters from a character string in Python?
A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
An easy way to view the time taken in Python and a smarter way to improve it