frhling
frhling

Reputation: 49

traverse upward on a directory structure until it gets to the file system top level

I have already created a script which sets "FLAG" after backup on uppermost level of each directory.

now I need a script that could be run "in any directory" and that would tell me "when the last successful backup ran" by reading the last modification time of the "FLAG".

Of course I can also manually find out on what file system my current directory is located and then go up in the directory hierarchy until I get to the file system's top level directory and find the flag file there but that is not very convenient. The command that I would like to write would do the same thing, but automatically.

1) I do not know how to do the part where it traverses upward on a directory structure until it gets to the file system top level.

2) reading the Flag time might work sth like this:

import time
fileTileInSeconds = os.path.getmtime("FLAG")   (not sure)
ModDate = time.localtime(fileTileInSeconds)
print ModDate.tm_year,ModDate.tm_mon,ModDate.tm_mday,ModDate.tm_hour,ModDate.tm_min,ModDate.tm_sec
quit()

Any idea/suggestion would be appreciated.

Upvotes: 2

Views: 754

Answers (1)

Peter Westlake
Peter Westlake

Reputation: 5036

Use os.path.parent to go up the directory tree, and use os.stat to see which device each directory is on. When the device changes, you have crossed the boundary of the filesystem. Like this:

#!/usr/bin/python

import os
import stat
import sys

def find_mount(path):
    path = os.path.realpath(path)
    s = os.stat(path)[stat.ST_DEV]
    ps = s
    while path != '/' and ps == s:
        parent = os.path.dirname(path)
        ps = os.stat(parent)[stat.ST_DEV]
        if ps == s:
            path = parent
    return path

if __name__ == "__main__":
    for path in sys.argv[1:]:
        print find_mount(path)

Upvotes: 1

Related Questions