4

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

3 Answers 3

5

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

1

Note that the imp module was deprecated with Python 3.

The equivalent can be done with importlib.

import importlib.util

spec = importlib.util.spec_from_file_location('myfile', '/path/to/myfile.py')
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)

print(mod.variable_a)
print(mod.variable_b)

Comments

0

The Cleanest way to use with using Python 2.7

import imp
module = imp.load_source("myfile", os.path.join(latest, "myfile.py"))
print(module.myvariable)
New contributor
Abdul Rameez K R is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Comment

That seems to be what the accepted answer already said. Did you have anything new to add?

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.