access Bash environment variable in Python using s

2019-09-19 19:07发布

问题:

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.