如何在Yaml文件中提及Mac Home文件夹

时间:2020-05-06 08:35:05

标签: python macos yaml

有人可以告诉我如何在yaml文件中提及Mac Home文件夹吗?

我有一个settings.yaml文件,该文件在我的Python代码中用于连接到GDrive。它将凭据导出到JSON文件,我希望将其提取到主目录中的GDrive文件夹。

settings.yaml

    client_config_backend: 'settings'
    client_config:
      client_id: "something"
      client_secret: "something"
      auth_uri: "https://accounts.google.com/o/oauth2/auth"
      token_uri: "https://oauth2.googleapis.com/token"

    save_credentials: True
    save_credentials_backend: 'file'
    save_credentials_file: '/Users/machinename/GDrive/credentials.json'

在python文件中,像这样被提及:

gauth = GoogleAuth(settings_file='settings.yaml')
gauth.LoadCredentialsFile('/Users/machinename/GDrive/credentials.json')

因此,不同的人将在不同的计算机上运行此命令,并且machinename将有所不同,因此我尝试为Home目录提供动态版本。我尝试了~/GDrive/credentials.json,但是没有用。

有人可以帮助您在yaml文件中声明主目录吗?

2 个答案:

答案 0 :(得分:1)

主文件夹表示为~
问题是您需要扩展,并且可以使用os

import os

os.path.expanduser("~/GDrive/credentials.json")

更新

如果要将其存储在yaml代码中,则是同一回事:

settings.yaml

client_config_backend: 'settings'
client_config:
  client_id: "something"
  client_secret: "something"
  auth_uri: "https://accounts.google.com/o/oauth2/auth"
  token_uri: "https://oauth2.googleapis.com/token"

save_credentials: True
save_credentials_backend: 'file'
save_credentials_file: '~/GDrive/credentials.json'

然后,在python中:

credentials_file = "settings.yaml"
with open(credentials_file, "r") as f:
    credentials_info = yaml.load(f)
gauth = GoogleAuth(settings_file=credentials_file)
gauth.LoadCredentialsFile(os.path.expanduser(credentials_info['save_credentials_file'))

答案 1 :(得分:0)

这可以实现您想要的

In settings.yaml
    save_credentials_file: '$HOME/GDrive/credentials.json'
...
In python, put '$HOME/GDrive/credentials.json' into variable save_credentials_file,

gauth.LoadCredentialsFile(os.path.expandvars(save_credentials_file))