Newbie: problem comparing values

Drew Fisher drew at level3.net
Mon Oct 8 21:51:13 CEST 2001


> Hi,
> 
> I'm trying to set up a script to check to see whether the person running
> the script is root or not.  If they are, I want to make it exit
> immediately.  This is the code that I have that I'm trying to use:
> 
> 
> user = os.popen("whoami").read()
> if user == "root":
>   print "You are logged in as root"
> else:
>   print "You are not logged in as root."
> 
> 
> The problem is that each time, no matter if it's root or not that's
> running the script, it always says "You are not logged in as root." I
> know that this has to be something small that I'm missing, and please
> forgive me for asking such a "simple" question, but I've only been at
> this for a couple of days (with python.  I have a few months of
> experience with bash scripts).  I've checked about every resource I can
> think of and I still can't figure out what I'm doing wrong.
> 
> Thanks in advance for your help,
> Jeremy
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list


When you use the read() command, you are forgetting that the newline
character is present in the output:

	
	>>> import os
	>>> user = os.popen("whoami").read()
	>>> user
	'drew\n'
	>>> 

You can solve your problem by either

	a)  stripping of the newline character at the end of the output

	user = os.popen ("whoami").read().strip()

or

	b)  comparing with the "\n" 

	if user == 'root\n":
		print "You are logged in as root"
	else:
		print "You are not logged in as root."


Hope this helps

Drew
-- 
Hell is other people's Perl.
	-- Linux Journal




More information about the Python-list mailing list