Python Forum

Full Version: Need help reducing some code around a subprocess
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi y'all!

I am trying to make a little script to help me practice some basic stuff, one of the things is that I wan't to be able to use my username on my OS (macOS Mojave 10.14.5, if that makes a difference) as a variable.

To do this I imported subprocess and used 'check_output' from the command that would give me the information 'id -un' and parsed(? sorry if I am using wrong terminology, I am still pretty new to programming) it into a variable, as shown in line 1. Problem is that the output from 'check_output' is apparently a bytes object, which includes what is shown on line 1 of the output below.

So to remove the b' prefixed and /n suffixed to my username, I decoded it and parsed that into a new variable, as shown in line 2. That removes the characters, but the line break is still there, as shown on line 2 and 3 of the output.

So I stripped the line break and parsed that into yet another variable, as shown in line 3. Which resulted in me getting the result I wanted, as seen in line 4 of the output.

user_bytesobject = subprocess.check_output("id -un", shell=True)
user_decoded = user_byteobject.decode()
user_name = user_decoded.strip('\n')
Output:
1| b'username\n' 2| username 3| 4| username
But that hardly seems like an efficient way of doing this. So my question is if there is a better way of getting my username into a variable?

Any help and other input would be much appreciated.
Try
name = subprocess.check_output(['id', '-un']).decode().strip()
If your python is more recent than 3.6, you can also use encoding='utf8' in the argument list of check_output(). Then you don't need decode().
Can show one with run() that has gotten new parameters like capture_output=True.
name = subprocess.run(['id', '-un'], encoding='utf8', capture_output=True)
(Jun-11-2019, 10:42 PM)snippsat Wrote: [ -> ]Can show one with run() that has gotten new parameters like capture_output=True.
name = subprocess.run(['id', '-un'], encoding='utf8', capture_output=True)

I tried this, but it gave me something that doesn't look like an error, but also not what I was looking for :P

Output:
CompletedProcess(args=['id', '-un'], returncode=0, stdout='username\n', stderr='')
But Gribouillis proposal worked, so are gonna mark the thread as solved.

Thank you both for your help and time!
(Jun-12-2019, 02:10 PM)anistorian Wrote: [ -> ]I tried this, but it gave me something that doesn't look like an error, but also not what I was looking for :P
I forgot to call stdout.
name = subprocess.run(['id', '-un'], encoding='utf8', capture_output=True)
print(name.stdout)