Jmilicev Jmilicev -4 years ago 118
Python Question

Using Python 2.7 to call an application in a sub folder of the folder containing the .py

I was wondering if there was a way to call an external application that is in the sub folder of the existing folder (To look like Figure 1, And not Figure 2). Im aware I can have it open a specific file path, however I need this to work on ANY computer when the folder is in ANY directory, Which simply would not work in when on another computer.

Figure 1:
https://gyazo.com/4c98428836e03e0b7a3e2c6bf2c0d9e1

Figure 2:
https://gyazo.com/8e0263ee7918e2fa26653a1dcc6187c7

I'm currently using code that looks like this to launch them, But it only works when its in the same folder:

def Button3():
os.startfile('procexp.exe')
def Button4():
os.startfile('IJ.exe')
def Button5():
os.startfile('Br.exe')
def Button6():
os.startfile('Cs.exe')


Sorry if this seems as a bit of a newbie question, But it would really help me out if I got an answer on this

Answer Source

Just add the relative path:

. means starting from present-working-directory (usually the location where the program is launched from).

So if you are launching the main program from the same folder that it's in then:

def Button3():
    os.startfile('./resources/procexp.exe')
def Button4():
    os.startfile('./resources/IJ.exe')
def Button5():
    os.startfile('./resources/Br.exe')
def Button6():
    os.startfile('./resources/Cs.exe')

However that's not usually the case, most of the time you would launch the program from wherever you are (either because it's in your PATH environment) or by supplying the full path to it. In that case you want to figure out where the program is installed and then figure out where you put the resources relative to it:

the special variable __file__ contains where your script is including the path to it. You can get the directory name by using dirname method in the os.path package:

     program_dir = os.path.dirname(__file__)

You can then work relative to that:

     resource_dir = os.path.join(program_dir, 'resources')

os.path.join is a way to join path bits together in a operating system agonstic way.

So eventually your program can become:

     resource_dir = os.path.join(os.path.dirname(__file__), 'resources');

def Button3():
    os.startfile(os.path.join(resource_dir, 'procexp.exe'))
def Button4():
    os.startfile(os.path.join(resource_dir, 'IJ.exe'))
def Button5():
    os.startfile(os.path.join(resource_dir, 'Br.exe'))
def Button6():
    os.startfile(os.path.join(resource_dir, 'Cs.exe'))

etc.

Of course in order to use os.path you need to import it:

  import os;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download