0

Good Afternoon

I'm currently trying to create a script that uses os.popen to access the MacOS application folder, check the version of a program, and then output the version. If the program is not found, the program outputs "[program] is not installed." However, I cannot quite figure out how to differentiate between a version number and the output being "could not find [program name]."

import os

def grab_version(target_app):
    stream = os.popen('mdls -raw -name kMDItemVersion /Applications/' + target_app + '.app')
    target_version = stream.read()
    read_out = target_app + " is installed, version " + target_version
    if target_version == "/Applications/" + target_app + ".app: could not find /Applications/" + target_app + ".app.":
        read_out = target_app + " is not installed."
        print(read_out)
    else:
        print(read_out)
    return()

grab_version("Slack")

This is my current attempt, trying to do an if/else where if is equal to the error message. I don't think that's a good solution, since it doesn't work.

Does anyone have any ideas? I have looked into exception handling but I don't think the "not found" error is considered an exception as it just writes to target_app anyway. I could be wrong, though.

  • It's likely that the string you're reading ends in a newline, or otherwise has some slight difference from the exact string you're comparing it to. Try something less specific: `"could not find" in target_version` perhaps. – jasonharper Jul 20 '22 at 16:14

1 Answers1

0

I figured out how I can do this. I used the "in" operator to find "could not find" in the string.

Here's the code:

 if "could not find" in target_version:
        read_out = target_app + " is not installed."
        print(read_out)
    else:
        read_out = target_app + " is installed, version " + target_version
        print(read_out)