3

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

1 Answer 1

4

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
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.