python - 在损坏的符号链接(symbolic link)的 Python 中更改 mtime

标签 python linux macos posix symlink

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

最佳答案

虽然跨平台并不容易,但可以使用 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))

关于python - 在损坏的符号链接(symbolic link)的 Python 中更改 mtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34779587/

相关文章:

linux - 来自 Xlib : "Killed" 的消息来源

c++ - 如何在 MacOS 上的 C++ 中设置 double ?

python - 为什么 re.VERBOSE 会阻止我的正则表达式模式工作?

python - 无法将标准输出复制到 python 中的文件

python - 如何将文件夹中的所有 .csv 文件转换为具有多个工作表选项卡(每个 .csv 1 个)的单个 .xlsx 文件?

java - 如何在linux服务器上通过java程序查看oracle监听器状态

python - 跨多个测试脚本模拟 Python 模块

linux - 如何将多行回显到来自 grep 结果的文件中

macos - pg gem 找不到 native 扩展——使用 Homebrew 安装的 PostgreSQL

linux - 默认端口号始终为 4 位数字