101010
101010

Reputation: 15716

How to import a Python module into a local variable using an arbitrary path?

I'm trying to use a python file as a config file. In my real program, I let the user specify the config file at the command line.

Here's my example:

some_randomly_named_file.py:

import os
from datetime import timedelta

PROJECT = "my project"
ENABLED_FORMATS = ['xml', 'json', 'yaml']
EXPIRATION=3600

#DEBUG = True
#TESTING = False

LOG_FOLDER = os.path.join(os.path.expanduser('~'), 'logs')

The file is stored here: /foo/bar/baz/some_randomly_named_file.py

...and then in myapp.py:

# parse the command line and get the path
path_to_file = '/foo/bar/baz/some_randomly_named_file.py'

# load the python file at path_to_file into local variable myconfig
# [What do I write here to accomplish this?]

# And now we have a local variable called myconfig
print(myconfig.PROJECT)

Output:

my project

Upvotes: 1

Views: 245

Answers (3)

sandeep nagendra
sandeep nagendra

Reputation: 522

Try adding your path to sys.path

Ex: if your config file is myconfig.py and present under /foo/bar/baz.

import sys
sys.path.append("/foo/bar/baz/")
import myconfig
local_var = myconfig.PROJECT

You can use os.path.basename() and os.path.dirname() to retrieve the values entered by user.

Sample program to get config filename and directory path from User

test.py

import sys
import os

file_path = sys.argv[1]
dir_name = os.path.dirname(file_path)
file_name = os.path.basename(file_path)

sys.path.append(dir_name)
print dir_name
print file_name

Output

#python test.py /var/log/syslog
/var/log
syslog

Upvotes: 1

101010
101010

Reputation: 15716

I found the solution based on an answer from @Redlegjed in this SO article.

Here it is modified a bit:

import os
import importlib.machinery

path_to_file = '/foo/bar/baz/some_randomly_named_file.py'

module_dir, module_file = os.path.split(path_to_file)
module_name, module_ext = os.path.splitext(module_file)

x = importlib.machinery.SourceFileLoader(module_name, path_to_file).load_module()

print(myconfig.PROJECT)

A list of related and helpful articles:

How to import a module given the full path?

Python 3.4: How to import a module given the full path?

Import arbitrary python source file. (Python 3.3+)

Upvotes: 0

semore_1267
semore_1267

Reputation: 1437

Like @sandeep mentioned. Just add your source file (config.py) to your sys path. When you add this config.py file to your path, Python treats the file (and its contents) like an ordinary module. Here's a bit more of an explanation:

# Load your config.py as a module
import sys
sys.path.append("/foo/bar/baz/") # Path to config.py parent folder

import config # Import as a regular module

print(config.PROJECT)
"my project"

You can use this very similar question for reference.

Upvotes: 2

Related Questions