I have a python file input.py
. There are comments and a mix of spaces and tabs, just for good measure.
# comment1 or header
name = "project1"
length = 100.0 # comment2
width = 20.0
area = length * width
circumference = 2*length + 2*width
# orphaned comment
I want to read the variables, some of which are evaluated from others, into my class structure so that they can be accessed like self.area
:
import importlib
class Project:
def __init__(self, inFile):
self.inFile = inFile
## from self.inFile import * # definitely not gonna work!
importlib.import_module(inFile) # doesn't work either!
p1 = Project(r"/home/feedme/input.py")
print p1.area
Desired example output:
2000.0
Aside from the fact that from something import *
is generally not a good idea, what can I use to bring the variables into the class in this way?
Edit: removed the side question about importing a module where the name is a string, since I found the answer already myself; importlib
.
I'd suggest using the runpy
module. The following will execute the python script at the path passed to the class initializer and load all of the non-dunder variables into the instance dictionary:
import runpy
class Project(object):
def __init__(self, path):
module = runpy.run_path(path)
for k, v in module.items():
if not k.startswith('__'):
self.__dict__[k] = v
For example:
>>> project = Project('conf.py')
>>> project.area
2000.0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.