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:

Figure 2:

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

def Button3():
def Button4():
def Button5():
def Button6():

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():
def Button4():
def Button5():
def Button6():

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'))


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