Search code examples
pythonpdfpdf-viewer

Finding the path to a pdf-viewer


I am only given the name of some pdf-viewer.

1) I want to check, if this pdf-viewer exists.

2) If this pdf-viewer exists, I want to find the path to it.

I am not sure how I have to approach.


Solution

  • If you are in Linux, you can use terminal commands. If the PDF viewer has a command-line tool you could do something simple like so:

    import subprocess
    check = subprocess.check_output(['which', 'ls'])
    print check
    

    Otherwise, you could run an OS independent walk and search filenames like so:

    import os
    
    matches = []
    for root, dirs, files in os.walk(os.path.join('path', 'to', 'search'):
        for file in files:
            if 'pdf-viewer' in file.lower():
                filepath = os.path.join(root, file)
                matches.append(filepath)
    
    print matches
    

    This will walk all the directories starting at '/path/to/search' on Mac/Linux, or \path\to\search on PC. It will search all filenames within each directory for a match, ignoring case in this example. If a match is found, it will recreate the absolute path of the current directory and matched filename, and append it to your matches list. Then you can do what you want with the list of matches.

    There's lots of info on how to use the os.Walk() function, but if you are on Python 2.7 I would recommend installing ScanDir, which is much faster (default for Python 3).