我看到如果我们更改HOME(linux)或USERPROFILE(windows)环境变量并运行python脚本,它会在我尝试时将新值作为用户主页返回,os.environ ['HOME'] os.exp
有没有办法找到真正的用户主目录而不依赖于环境变量?
编辑:
这是一种通过在注册表中阅读http://mail.python.org/pipermail/python-win32/2008-January/006677.html在Windows中查找userhome的方法
编辑:
使用pywin32查找windows的一种方法,
from win32com.shell import shell,shellcon
home = shell.SHGetFolderPath(0, shellcon.CSIDL_PROFILE, None, 0)
Run Code Online (Sandbox Code Playgroud) 我想访问/home/weasel从那里读取一些文件,但我不想写完整的路径 - 所以其他用户可以使用脚本..你怎么知道你的用户名或你的家庭目录与Linux上的python?
谢谢
我最近开始使用ConfigParser()为我的python脚本添加一些功能给它们配置文件.我知道如何使用它,但我有一个问题.我的脚本需要使用sudo作为root用户运行.配置文件在,~/.config/scriptconfig/但是当您以sudo身份运行脚本时,它会临时将用户更改为root,因此它找不到配置文件.我想要做的是获取有效用户的配置文件,以便抓取/home/myuser/.config/scriptconfig/config.cfg而/root/.config/scriptconfig/config.cfg不是存在.
我需要脚本能够在不同的机器上运行,而不仅仅是我的.所以我需要获得有效用户的主目录
这是我尝试使用的代码示例:
import os, ConfigParser
config = ConfigParser.RawConfigParser()
homepath = os.path.expanduser("~/")
configpath = homepath + ".config/scriptconfig/config.cfg"
config.read(configpath)
get = config.get('Config', 'Example')
print get
它应该打印example配置文件的值,但是当以sudo身份运行时,路径是/home/root这样,它找不到配置文件. 我的程序需要存储一些配置文件。主要的操作系统似乎都有一个指定的位置来放置它们;例如,在 Freedesktop.org 兼容系统上,它将是存储在$XDG_CONFIG_HOME环境变量中的路径。
是否有方法(或库)可以跨主要操作系统获取此配置主目录:Windows、OS X、Linux?
我尝试不为配置文件使用绝对路径,因为我需要在多个环境中部署该路径,这是我的最佳选择
以下代码是我尝试过的代码,它无法找到路径,但是我可以将文件放在同一位置。我在Redhat服务器上使用Python3.6。
with open("~/scripts/config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '~/scripts/config.yml'
Run Code Online (Sandbox Code Playgroud)