How to evaluate environment variables into a string in Python?(如何在 Python 中将环境变量评估为字符串?)
问题描述
我有一个代表路径的字符串.因为这个应用程序在 Windows、OSX 和 Linux 上使用,我们已经定义了环境变量来正确映射来自不同文件系统的卷.结果是:
I have a string representing a path. Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems. The result is:
"$C/test/testing"
我想要做的是评估字符串中的环境变量,以便将它们替换为各自的卷名.是否有我遗漏的特定命令,或者我必须采取 os.environ.keys()
并手动替换字符串?
What I want to do is evaluate the environment variables in the string so that they're replaced by their respective volume names. Is there a specific command I'm missing, or do I have to take os.environ.keys()
and manually replace the strings?
推荐答案
使用 os.path.expandvars 展开字符串中的环境变量,例如:
Use os.path.expandvars to expand the environment variables in the string, for example:
>>> os.path.expandvars('$C/test/testing')
'/stackoverflow/test/testing'
这篇关于如何在 Python 中将环境变量评估为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中将环境变量评估为字符串?


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01