You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSL Ubuntu环境下Python调用Firebase密钥文件提示找不到的解决方法

解决WSL中Firebase私钥文件找不到的问题

我来帮你搞定这个问题!你遇到的核心原因是Python不会自动解析路径里的~(波浪号)——这个符号只有Shell(比如bash)才会识别成用户主目录,Python会直接把它当作路径的一部分,所以自然找不到文件。下面是几个可行的解决方案:

方案1:使用完整的绝对路径

直接写死WSL里的绝对路径,不用依赖~。首先在WSL的终端里,进入你的工作目录:

cd ~/projects/scrape

然后执行pwd命令,会输出类似/home/your-username/projects/scrape的绝对路径(把your-username换成你的WSL用户名)。接着把这个路径加上文件名,替换到代码里:

import requests
from bs4 import BeautifulSoup
import firebase_admin
from firebase_admin import credentials, firestore

# 替换成你自己的绝对路径
cred = credentials.Certificate("/home/your-username/projects/scrape/serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()

方案2:用Python的os.path.expanduser()解析波浪号

导入os模块,让Python帮你把~转换成实际的用户主目录,这样代码更灵活:

import requests
from bs4 import BeautifulSoup
import os  # 新增os模块
import firebase_admin
from firebase_admin import credentials, firestore

# 用expanduser处理带~的路径
cred_path = os.path.expanduser("~/projects/scrape/serviceAccountKey.json")
cred = credentials.Certificate(cred_path)
firebase_admin.initialize_app(cred)
db = firestore.client()

方案3:使用相对路径(最简洁)

如果你的Python脚本就是在~/projects/scrape目录下运行的,那直接写文件名就行,Python会自动在当前工作目录找文件:

import requests
from bs4 import BeautifulSoup
import firebase_admin
from firebase_admin import credentials, firestore

# 直接写文件名,前提是脚本在同一目录运行
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()

小提示:可以在脚本里加一行print(os.getcwd()),看看Python当前的工作目录是不是你的项目文件夹,避免路径错位。

最后再验证一下:在WSL终端里执行ls ~/projects/scrape/serviceAccountKey.json,如果能看到文件名,说明文件确实在那里,用上面的方法肯定能解决问题~

内容的提问来源于stack exchange,提问作者U. Watt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 00:47:41