Python os.path.expandvars only works for some variables

别说谁变了你拦得住时间么 提交于 2021-02-17 06:00:06

问题


Running os.path.expandvars fails for some env variables. Seems too basic to be real.

$ echo $HOSTTYPE 
x86_64
$ echo $HOME     
/labhome/eladw
$ python -c 'import os; print os.path.expandvars("$HOSTTYPE")'
$HOSTTYPE
$ python -c 'import os; print os.path.expandvars("$HOME")'
/labhome/eladw

Any idea what I'm missing (I am running python 2.7)?


回答1:


Environment variables set in a shell are not automatically exported to subprocesses. Just because your shell has a HOSTTYPE variable, doesn't mean this is variable is visible to subprocesses.

Export the variable first:

$ export HOSTTYPE

You can combine setting and exporting a variable in one step with:

$ export HOSTTYPE=x86_64

Demo:

$ HOSTTYPE=x86_64
$ python -c 'import os; print os.path.expandvars("$HOSTTYPE")'
$HOSTTYPE
$ export HOSTTYPE
$ python -c 'import os; print os.path.expandvars("$HOSTTYPE")'
x86_64

See Difference between environment variables and exported environment variables in bash.



来源:https://stackoverflow.com/questions/50857962/python-os-path-expandvars-only-works-for-some-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!