Search code examples
pythonregexstringpopenequivalence

Why can't I check for string equivalence against stderr of Popen() in Python?


I'm running an ldaplist command from a Python script (not doing enough to warrant the ldap module):

storage = Popen(["ldaplist", "-l", "passwd", "bob"], stdout=PIPE, stderr=PIPE)
stdout, stderr = storage.communicate()

After this, I'd like to take action based on whether or not "stderr" matches the typical "no such user" error from ldaplist (which is "ldaplist: Object not found")

This does not work:

if stderr == "ldaplist: Object not found":
   print "No entry exists in passwd for the username you have input."
   sys.exit(1)

This, however, does:

if re.search("^ldaplist: Object not found", stderr):
   print "No entry exists in passwd for the username you have input."
   sys.exit(1)

By, "does not work," I mean that it does not fall into the if block, and therefore it goes on to execute the rest of the code and runs into all sorts of errors because the remainder of code is expecting stdout to be populated (which it's not if there's any value for stderr).

I don't think it relates to my snippet above that is failing, but the error specifically is:

Traceback (most recent call last):
  File "./ldaplistTest3.py", line 43, in <module>
    testPasswd = Passwd(dn, sambaProfilePath, sambaHomePath)
NameError: name 'dn' is not defined

(dn is not defined because the code should have never gotten to that point)


Solution

  • repr is a very handy built-in function, esp. for debugging purposes. You can often use it to find easy-to-overlook whitespace and things which look like spaces but aren't, etc.

    In this case, it should (and apparently did :^) show that there's some trailing whitespace giving you trouble.

    FWIW I often call .strip() before doing string comparisons to avoid some of these issues.