Need help reducing some code around a subprocess - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Need help reducing some code around a subprocess (/thread-19055.html) |
Need help reducing some code around a subprocess - anistorian - Jun-11-2019 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') 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. RE: Need help reducing some code around a subprocess - Gribouillis - Jun-11-2019 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().
RE: Need help reducing some code around a subprocess - snippsat - Jun-11-2019 Can show one with run() that has gotten new parameters like capture_output=True .name = subprocess.run(['id', '-un'], encoding='utf8', capture_output=True) RE: Need help reducing some code around a subprocess - anistorian - Jun-12-2019 (Jun-11-2019, 10:42 PM)snippsat Wrote: Can show one with I tried this, but it gave me something that doesn't look like an error, but also not what I was looking for :P But Gribouillis proposal worked, so are gonna mark the thread as solved.Thank you both for your help and time! RE: Need help reducing some code around a subprocess - snippsat - Jun-12-2019 (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 :PI forgot to call stdout .name = subprocess.run(['id', '-un'], encoding='utf8', capture_output=True) print(name.stdout) |