eatonphil
eatonphil

Reputation: 13722

Error getting abspath for Windows 7 with Python

I keep getting a 'cannot find file' error when trying to run this. Why is it not finding and assigning the absolute path? Here is my code:

    file = "/" + arr[2] + ".exe"
    print(file)
    path = os.path.abspath(file)
    print(path)
    subprocess.Popen(path)
    localtime = time.asctime(time.localtime(time.time()))
    print(arr[2] + " opened at " + localtime + "\n")

Here is what is outputted:

/firefox.exe
C:\firefox.exe
Traceback (most recent call last):
File "C:\Python33\lib\subprocess.py", line 1090, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

I am trying to programmatically find open a program based on user input... Maybe I am going about that the wrong way, but this is how somebody suggested doing it. Firefox.exe should be located at C:/Program Files/Firefox/firefox.exe

Any help would be great! Thanks!

Upvotes: 0

Views: 1123

Answers (2)

Freezerburn
Freezerburn

Reputation: 1013

One solution for attempting to open a program on Windows is to just search all folders, starting from the base directories of C:/Program files/ and C:/Program Files (x86). A simple solution to this might be something like the following:

for program_files in (os.path.join("C:", "Program\ Files"), os.path.join("C:", "Program\ Files\ (x86)"):
    for dir in os.listdir(program_files):
        if os.path.exists(os.path.join(program_files, dir, arr[2]) + ".exe"):
            subprocess.Popen(os.path.join(program_files, dir, arr[2]) + ".exe")

This only walks one directory down into the Program Files directories, but it should at least give a gist of what needs to be done, as well as provide a simple solution for most cases. I would assume that most programs tend to keep their executable under the first directory.

As a quick side note: if you are creating an application that can be run on both 32bit and 64bit versions of Windows, you will want some kind of check for the existence of the Program Files (x86) directory, or some kind of check for 32 vs 64 bit Windows. That folder only exists on 64 bit versions of Windows.

Also: the reason your method didn't work is because you were getting the abspath of /firefox.exe, which on a Unix system signifies the lowest-level directory on the computer. On Windows, that would be C:/. Python generally works in a very Unix-ey way, so it assumes you wanted the root directory of your system.

Upvotes: 3

John
John

Reputation: 13709

Once I had attianed the paths this is how I would launch the programs, however file walking/search algorithms is beyond the scope of this question.

#load this from a setting file later
programDict = {'firefox': r"C:/Program Files/Firefox/firefox.exe"}

if sys.argv[2] in programDict:
    subprocess.Popen(path)

Upvotes: 0

Related Questions