Segfaulter
Segfaulter

Reputation: 73

Import Variable from Python FilePath

I'm writing a clean up script from one of our applications and I need a few variables from a python file in a separate directory.

Now normally I would go:

from myfile import myvariable
print myvariable

However this doesn't work for files outside of the directory. I'd like a more targeted solution than:

sys.path.append('/path/to/my/dir)
from myfile import myvariable

As this directory has a lot of other files, unfortunately it doesn't seem like module = __import__('/path/to/myfile.py') works either. Any suggestions. I'm using python 2.7

EDIT, this path is unfortunately a string from os.path.join(latest, "myfile.py")

Upvotes: 3

Views: 2055

Answers (1)

Wokpak
Wokpak

Reputation: 593

You can do a more targeted import using the imp module. While it has a few functions, I found the only one that allowed me access to internal variables was load_source.

import imp
import os

filename = 'variables_file.py'
path = '/path_to_file/'

full_path = os.path.join(path_to_file, filename)

foo = imp.load_source(filename, full_path)

print foo.variable_a
print foo.variable_b
...

Upvotes: 4

Related Questions