user2425345
user2425345

Reputation: 31

How to get the path of a program in python?

I'm doing a program in which Chimera needs to be opened, I'm opening it with:

def generate_files_bat(filename):
    f = open(filename, 'w')
    text = """echo off SET PATH=%PATH%;"C:\\Program Files (x86)\\Chimera 1.6.1\\bin" chimera colpeps.cmd"""
    print >>f, text
    f.close()

But I need to find Chimera apart from the computer the python program is running. Is there any way the path can be searched by the python program in any computer?

Upvotes: 0

Views: 2145

Answers (3)

Sylvain Leroux
Sylvain Leroux

Reputation: 51990

Generally speaking, I don't think it is such a good idea to search the path for a program. Imagine, for example that two different versions were installed on the machine. Are-you sure to find the right one? Maybe a configuraition file parsed with the standard module ConfigParser would be a better option?

Anyway, to go back to your question, in order to find a file or directory, you could try to use os.walk which recursively walks trough a directory tree.

Here is an example invoking os.walk from a generator, allowing you to collect either the first or all matching file names. Please note that the generator result is only based on file name. If you require more advanced filtering (say, to only keep executable files), you will probably use something like os.stat() to extend the test.

import os

def fileInPath(name, root):
    for base, dirs, files in os.walk(root):
        if name in files:
            yield os.path.join(base, name)

print("Search for only one result:")
print(next(fileInPath("python", "/home/sylvain")))

print("Display all matching files:")
print([i for i in fileInPath("python", "/home/sylvain")])

Upvotes: 1

LarsVegas
LarsVegas

Reputation: 6812

There is a package called Unipath, that does elegant, clean path calculations.

Have look here for the AbstractPath constructor

Example:

from unipath import Path
prom_dir = Path(__file__)

Upvotes: 0

Johannes Jasper
Johannes Jasper

Reputation: 921

There is which for Linux and where for Windows. They both give you the path to the executable, provided it lies in a directory that is 'searched' by the console (so it has to be in %PATH% in case of Windows)

Upvotes: 0

Related Questions