Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess.Popen result stored in a variable

I've seen various other posts about this, but unfortunately I still haven't been able to figure this out:

If I do something like this:

temp = subprocess.Popen("whoami", shell=True, stdout=subprocess.PIPE)
out = temp.communicate()
print(out)

then I get something of the form

(b'username\n', None)

With other attempts (such as adding a .wait()) I've been getting the username on one line, and a 0 as a return code on the next, however only the 0 was being stored in my variable.

Is there an easy way I can format that to store only the username in a variable? I tried something like out[3:11] but that didn't work.

Thanks

like image 656
Matt Avatar asked Nov 01 '25 17:11

Matt


1 Answers

The easiest way is to use subprocess.check_output():

username = subprocess.check_output("whoami").strip()
like image 71
Sven Marnach Avatar answered Nov 03 '25 12:11

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!