【问题标题】:Change mtime within Python of a broken symlink在 Python 中更改损坏符号链接的 mtime
【发布时间】:2016-04-19 04:31:42
【问题描述】:

显然没有像os.lutime 这样允许更改符号链接本身的mtime,即使它指向的文件不存在。为此,在 Linux 和 OSX 上,touch 命令具有 -h 选项以不取消引用链接。但是我发现没有办法在 Python 中实现本机跨平台(至少在 OSX 和 Linux 上)。那么有没有办法解决我的欲望呢? ;)

【问题讨论】:

    标签: python linux macos posix symlink


    【解决方案1】:

    虽然不容易跨平台,但可以使用ctypes模块调用原生函数来做到这一点。

    这是我为在 macOS 上执行此操作而创建的 Python 2 代码。我想通过一些调整,它也可以在 Linux 上运行。

    import ctypes
    import ctypes.util
    
    class ctype_timeval(ctypes.Structure):
        _fields_ = [
            ('tv_sec', ctypes.c_long),
            ('tv_usec', ctypes.c_long)
        ]
    
    ctype_libsystemc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('libsystem.c'))
    ctype_libsystemc_lutimes = ctype_libsystemc.lutimes
    ctype_libsystemc_lutimes.restype = ctypes.c_int
    ctype_libsystemc_lutimes.argtypes = [ctypes.c_char_p, ctype_timeval * 2]
    
    def lutime(filename, time):
        times = (ctype_timeval * 2)()
        # access:
        times[0].tv_sec = time[0]
        times[0].tv_usec = 0
        # modification:
        times[1].tv_sec = time[1]
        times[1].tv_usec = 0
    
        return ctype_libsystemc_lutimes(filename, times)
    

    你可以像os.utime一样使用它:

    lutime('file-or-symlink', (1488079452, 1488079452))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多