2

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?

5
  • 2
    Why do you want to use subprocess? The python process itself has access to the environment. Commented Jul 3, 2014 at 17:35
  • 3
    You can use os.environ for this. e.g. print(os.environ['USER']) Commented Jul 3, 2014 at 17:36
  • Thank you very much for your suggestions. Part of the motivation is wanting to understand how to use Bash variables in subprocess methods. I am not sure how to do this. Accessing the environment variable ${USER} is a simple example. Commented Jul 5, 2014 at 14:17
  • 1
    The thing is, calling Python subprocess with a bash-style variable name does not do any variable expansion, globbing, etc. There is no shell between Python subprocessing, and the argv/argc of the program you are invoking. Commented Jul 6, 2014 at 5:26
  • unrelated: there is shutil.get_terminal_size() function in Python 3.3+, to get width/height of the terminal. Commented Jul 26, 2014 at 14:31

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you very much for your suggestions on using the getenv and environ methods of the module os. This works well. Part of the motivation in wanting to use the module subprocess is wanting to understand how to use Bash variables in subprocess methods. I have tried your subprocess.Popen(['echo', '${USER}']) suggestion but am presented with '${USER}' as a response rather than the actual environment variable value in both Python 2.7.6 and 3.4.0. Do you know how to access the actual value?
Ah, great. Your edits have made that work. Thanks again for your help!
@Etan Reisner: do not use a list argument and shell=True together. Always pass a string if you use shell=True instead.
@J.F.Sebastian Would you care to enlighten me as to why? (I am by no means a python person.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.