[Tutor] Check if root
Kent Johnson
kent37 at tds.net
Sat Sep 29 15:33:31 CEST 2007
Robert Jackson wrote:
> I'm trying to write a function that checks to see if the user that
> is running the python script is 'root' (I'm obviously running this
> Python program on Linux).
>
>
>
> Using os.system(), I have done something like this:
>
>
>>>> import os
>
>>>> os.system("whoami")
>
> robert
>
> 0
> If I try to assign the output of this snippet of code to a variable,
> the variable ultimately ends up holding "0" and not the username.
os.system returns the result code from the subprocess, not it's output.
Use the subprocess module when you want to capture output:
In [6]: from subprocess import Popen, PIPE
In [7]: Popen(['whoami'], stdout=PIPE).communicate()
Out[7]: ('kent\n', None)
In [8]: out, err = Popen(['whoami'], stdout=PIPE).communicate()
In [9]: out
Out[9]: 'kent\n'
Kent
More information about the Tutor
mailing list