Search code examples
pythonerror-handlingnonetype

Handle the NoneType exception in custom code


My code:

def getVersion(DownloadFile,rel,dll):
   q = "(Get-Item " + DownloadFile +").VersionInfo | Format-List | findstr ProductVersion"
   proc = subprocess.Popen(["powershell.exe", q], stdout=subprocess.PIPE)
   start = ': '
   end = '\''
   result = re.search('%s(.*)%s' % (start, end), str(proc.stdout.read().rstrip())).group(1)
   return (result)

The code is to run a powershell command and get the output to compare. In detail, it is to find the dll version with PowerShell. But for certain dll files powershell does not return any version (Gives a blank output), and then my python code panics and error out.

The error I am facing is :

result = re.search('%s(.*)%s' % (start, end), str(proc.stdout.read().rstrip())).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

I am looking for a way to tackle this.


Solution

  • Separate the match searching from the .group(1) call, then call .group(1) only if match exists:

    def getVersion(DownloadFile,rel,dll):
        q = "(Get-Item " + DownloadFile +").VersionInfo | Format-List | findstr ProductVersion"
        proc = subprocess.Popen(["powershell.exe", q], stdout=subprocess.PIPE)
        start = ': '
        end = '\''
        match = re.search('%s(.*)%s' % (start, end), str(proc.stdout.read().rstrip()))
        return match.group(1) if match else None