Pexe
Pexe

Reputation: 91

Start external program without hardcoding the path

I am making a GUI that is supposed to be run on different computers. In the script I need to open an external program and run a macro through this program.I am using subprocess to do so. The problem is that without hardcoding the path I am not able to find the program. I cannot hardcode the path, because the program might be in different directories on different computers. Is this possible to do?

Code:

from subprocess import *

def call_dos(self, program, *args):

    proc = call([program, args])
    if proc:
        logging.warning('Calling failed')
    else:
        logging.info('Calling successful')

def partone(self, *args):
    try:
        self.call_dos("Myprogram.exe", r"C:\Mymacro.mko")
    finally:
        self.partone()

The error message:

Traceback:
    'Calling failed'

Thank you for any replies!

Upvotes: 1

Views: 72

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140188

You have to check that Myprogram.exe is callable, i.e. in system path.

For windows, either set it in user or system environment by appending the actual directory where the exe is located to the PATH environment variable.

To make sure that users don't blame your program for their bad installation, you could add a check so the error is human-readable:

import distutils.spawn
if not distutils.spawn.find_executable("Myprogram.exe"):
     raise Exception("{} is not in the path, add it to path and retry".format("Myprogram.exe"))

You can also distribute the program alongside your script (same directory), so you're sure it's found (if doesn't need a deep installation). In that case, do:

self.call_dos(os.path.join(os.path.dirname(__file__),"Myprogram.exe"), r"C:\Mymacro.mko")

Upvotes: 1

Related Questions