You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python中os模块缺失getresuid()方法问题求助

问题原因与解决方案

为什么macOS上的Python找不到os.getresuid()os.getresgid()

这是因为CPython在macOS平台的os模块实现中,没有封装getresuid()getresgid()这两个系统调用。虽然macOS(基于BSD)底层内核支持这两个系统调用,但Python的标准库并没有在macOS版本的os模块里暴露这些方法——简单说就是Python维护者没给macOS版本的os模块加这两个方法的绑定,所以你用dir(os)看不到它们,调用时就会触发AttributeError

这个问题在pyenv安装的Python和系统自带的Python上都会出现,因为pyenv编译的Python也是遵循CPython的平台适配规则的。


解决方案:用ctypes直接调用底层系统调用

既然macOS底层支持getresuid()getresgid(),我们可以通过ctypes库直接调用系统的libc函数来获取这些值,替代os模块的方法。

获取UID相关信息(ruid/euid/suid)

import ctypes
import os

# 加载系统的libc库
libc = ctypes.CDLL('/usr/lib/libc.dylib')

# 定义存储三个UID的变量
ruid = ctypes.c_uint32()
euid = ctypes.c_uint32()
suid = ctypes.c_uint32()

# 调用getresuid系统调用
libc.getresuid(ctypes.byref(ruid), ctypes.byref(euid), ctypes.byref(suid))

# 输出结果
print(f"process ruid is {ruid.value}, euid is {euid.value}, suid is {suid.value}")

获取GID相关信息(rgid/egid/sgid)

# 定义存储三个GID的变量
rgid = ctypes.c_uint32()
egid = ctypes.c_uint32()
sgid = ctypes.c_uint32()

# 调用getresgid系统调用
libc.getresgid(ctypes.byref(rgid), ctypes.byref(egid), ctypes.byref(sgid))

# 输出结果
print(f"gid is {rgid.value}, egid is {egid.value}, sgid is {sgid.value}")

额外的代码修正提示

你的代码里还有一个逻辑小问题:os.setpgrp()在macOS上成功时返回0,失败返回-1,但你现在的判断是if success:就打印"get some problem here",这刚好搞反了。应该改成:

success = os.setpgrp()
if success == -1:
    print("get some problem here")

这样才能正确捕获setpgrp()调用失败的情况。


内容的提问来源于stack exchange,提问作者Neal.Marlin

火山引擎 最新活动