access Bash environment variable in Python using subprocess

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 14:44:11

问题


I can determine the width of the terminal in Python with a subprocess-handled query such as the following:

int(subprocess.Popen(['tput', 'cols'], stdout = subprocess.PIPE).communicate()[0].strip('\n'))

How could I determine the Bash user name in a similar way? So, how could I see the value of ${USER} in Python using subprocess?


回答1:


As Wooble and dano say, don't use subprocess for this. Use os.getenv("USER") or os.environ["USER"].

If you really want to use subprocess then Popen(['bash', '-c', 'echo "$USER"'], ...) seems to work as does Popen("echo $USER", shell=True) though neither of those is particularly pleasant (though to use environment variables on the command line being executed the shell must be involved so you can't really avoid it).

Edit: My previous subprocess suggestion did not seem to work correctly. I believe my original test was flawed.



来源:https://stackoverflow.com/questions/24559991/access-bash-environment-variable-in-python-using-subprocess

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