获取主目录的跨平台方式是什么?
我需要获取当前登录用户的主目录的位置。目前,我一直在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在Python 3.5+上,您可以使用 pathlib.Path.home():
获取一个
pathlib.PosixPath
对象。如有必要,请使用str()
转换为字符串。在较旧的 Python 版本上,您可以使用 os.path.expanduser。
On Python 3.5+ you can use pathlib.Path.home():
to get a
pathlib.PosixPath
object. Usestr()
to convert to a string if necessary.On older Python versions, you can use os.path.expanduser.
我发现pathlib模块也支持这个。
I found that pathlib module also supports this.
我知道这是一个旧线程,但我最近需要它来进行大型项目(Python 3.8)。它必须适用于任何主流操作系统,因此我采用了 @Max 在评论中写的解决方案。
代码:
输出 Windows:
输出 Linux (Ubuntu):
我也在 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:
Output Windows:
Output Linux (Ubuntu):
I also tested it on Python 2.7.17 and that works too.
这可以使用
pathlib
来完成,这是标准库的一部分,并将路径视为具有方法的对象,而不是字符串。Path.expanduser()
Path.home()
This can be done using
pathlib
, which is part of the standard library, and treats paths as objects with methods, instead of strings.Path.expanduser()
Path.home()
这并不真正符合这个问题(它被标记为
跨平台
),但也许这对某人有用。如何获取<的主目录强>有效用户(特定于Linux)。
假设您正在编写一个安装程序脚本或其他一些解决方案,要求您在某些本地用户下执行某些操作。您很可能会在安装程序脚本中通过更改有效用户来完成此操作,但 os.path.expanduser("~") 仍将返回
/root
。该参数需要具有所需的用户名:
请注意,上面的方法可以在不更改 EUID 的情况下正常工作,但如果前面描述的场景适用,下面的示例显示了如何使用它:
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:
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: