2020年10月1日 星期四

[ Python 常見問題 ] How to evaluate environment variables into a string in Python?

 Source From Here

Question
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:
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?

HowTo
Use os.path.expandvars to expand the environment variables in the string, for example:
>>> os.environ['VOLUME_PATH']='/tmp'
>>> os.path.expandvars('$VOLUME_PATH/abc')
'/tmp/abc'
>>> os.environ['VOLUME_PATH']='/tmp/test'
>>> os.path.expandvars('$VOLUME_PATH/abc')
'/tmp/test/abc'

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...