获取主目录的跨平台方式是什么?

发布于 2024-09-29 15:13:20 字数 173 浏览 6 评论 0原文

我需要获取当前登录用户的主目录的位置。目前,我一直在 Linux 上使用以下内容:

os.getenv("HOME")

但是,这在 Windows 上不起作用。执行此操作的正确跨平台方法是什么?

I need to get the location of the home directory of the current logged-on user. Currently, I've been using the following on Linux:

os.getenv("HOME")

However, this does not work on Windows. What is the correct cross-platform way to do this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

天煞孤星 2024-10-06 15:13:20

Python 3.5+上,您可以使用 pathlib.Path.home()

from pathlib import Path
home = Path.home()

# example usage:
with open(home / ".ssh" / "known_hosts") as f:
    lines = f.readlines()

获取一个pathlib.PosixPath对象。如有必要,请使用 str() 转换为字符串。


在较旧的 Python 版本上,您可以使用 os.path.expanduser

from os.path import expanduser
home = expanduser("~")

On Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = Path.home()

# example usage:
with open(home / ".ssh" / "known_hosts") as f:
    lines = f.readlines()

to get a pathlib.PosixPath object. Use str() to convert to a string if necessary.


On older Python versions, you can use os.path.expanduser.

from os.path import expanduser
home = expanduser("~")
记忆里有你的影子 2024-10-06 15:13:20

我发现pathlib模块也支持这个。

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')

I found that pathlib module also supports this.

from pathlib import Path
>>> Path.home()
WindowsPath('C:/Users/XXX')
彼岸花ソ最美的依靠 2024-10-06 15:13:20

我知道这是一个旧线程,但我最近需要它来进行大型项目(Python 3.8)。它必须适用于任何主流操作系统,因此我采用了 @Max 在评论中写的解决方案。

代码:

import os
print(os.path.expanduser("~"))

输出 Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

输出 Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

我也在 Python 2.7.17 上测试了它,这也有效。

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

import os
print(os.path.expanduser("~"))

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

满地尘埃落定 2024-10-06 15:13:20

这可以使用 pathlib 来完成,这是标准库的一部分,并将路径视为具有方法的对象,而不是字符串。

from pathlib import Path

home: str = str(Path('~').expanduser())

This can be done using pathlib, which is part of the standard library, and treats paths as objects with methods, instead of strings.

from pathlib import Path

home: str = str(Path('~').expanduser())
染年凉城似染瑾 2024-10-06 15:13:20

这并不真正符合这个问题(它被标记为跨平台),但也许这对某人有用。

如何获取<的主目录强>有效用户(特定于Linux)

假设您正在编写一个安装程序脚本或其他一些解决方案,要求您在某些本地用户下执行某些操作。您很可能会在安装程序脚本中通过更改有效用户来完成此操作,但 os.path.expanduser("~") 仍将返回 /root

该参数需要具有所需的用户名:

os.path.expanduser(f"~{USERNAME}/")

请注意,上面的方法可以在不更改 EUID 的情况下正常工作,但如果前面描述的场景适用,下面的示例显示了如何使用它:

import os
import pwd
import grp

class Identity():

    def __init__(self, user: str, group: str = None):
        self.uid = pwd.getpwnam(user).pw_uid
        if not group:
            self.gid = pwd.getpwnam(user).pw_gid
        else:
            self.gid = grp.getgrnam(group).gr_gid

    def __enter__(self):
        self.original_uid = os.getuid()
        self.original_gid = os.getgid()
        os.setegid(self.uid)
        os.seteuid(self.gid)

    def __exit__(self, type, value, traceback):
        os.seteuid(self.original_uid)
        os.setegid(self.original_gid)

if __name__ == '__main__':

    with Identity("hedy", "lamarr"):
        homedir = os.path.expanduser(f"~{pwd.getpwuid(os.geteuid())[0]}/")
        with open(os.path.join(homedir, "install.log"), "w") as file:
            file.write("Your home directory contents have been altered")

This doesn't really qualify for the question (it being tagged as cross-platform), but perhaps this could be useful for someone.

How to get the home directory for effective user (Linux specific).

Let's imagine that you are writing an installer script or some other solution that requires you to perform certain actions under certain local users. You would most likely accomplish this in your installer script by changing the effective user, but os.path.expanduser("~") will still return /root.

The argument needs to have the desired user name:

os.path.expanduser(f"~{USERNAME}/")

Note that the above works fine without changing EUID, but if the scenario previously described would apply, the example below shows how this could be used:

import os
import pwd
import grp

class Identity():

    def __init__(self, user: str, group: str = None):
        self.uid = pwd.getpwnam(user).pw_uid
        if not group:
            self.gid = pwd.getpwnam(user).pw_gid
        else:
            self.gid = grp.getgrnam(group).gr_gid

    def __enter__(self):
        self.original_uid = os.getuid()
        self.original_gid = os.getgid()
        os.setegid(self.uid)
        os.seteuid(self.gid)

    def __exit__(self, type, value, traceback):
        os.seteuid(self.original_uid)
        os.setegid(self.original_gid)

if __name__ == '__main__':

    with Identity("hedy", "lamarr"):
        homedir = os.path.expanduser(f"~{pwd.getpwuid(os.geteuid())[0]}/")
        with open(os.path.join(homedir, "install.log"), "w") as file:
            file.write("Your home directory contents have been altered")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文