import file without .py into another module
kevinbercaw at gmail.com
kevinbercaw at gmail.com
Tue Jan 21 10:50:40 EST 2014
On Tuesday, January 21, 2014 10:40:09 AM UTC-5, Peter Otten wrote:
> kevin... at gmail.com wrote:
>
>
>
> >> > How do I get the value of the config file variable "myVar"?? It seems
>
> >> > it's interpreting the variable name as a string rather than a variable
>
> >> > name. I don't see any python function stringToVariable.
>
>
>
> >> The line:
>
> >>
>
> >> configModuleObject = imp.load_source(fileName, filePath)
>
>
>
> >> imports the module and then binds it to the name configModuleObject,
>
> >>
>
> >> therefore:
>
> >>
>
> >> print configModuleObject.myVar
>
> >
>
> > Yep, I tried that right off as that's how I thought it would work, but it
>
> > doesn't work. Traceback (most recent call last):
>
> > File "mainScript.py", line 31, in <module>
>
> > print configModuleObject.myVar
>
> > AttributeError: 'module' object has no attribute 'myVar'
>
>
>
> Try again with
>
>
>
> module = imp.load_source("made_up_name", "a15800")
>
> print module.myVar
>
>
>
> If the file "a15800" is not in the current working directory, give the
>
> complete path, e. g:
>
>
>
> module = imp.load_source("made_up_name", "/path/to/a15800")
>
> print module.myVar
>
>
>
> The first arg serves as the module's name which is used for caching to speed
>
> up repeated imports:
>
>
>
> >>> import imp
>
> >>> import sys
>
> >>> "made_up_name" in sys.modules
>
> False
>
> >>> module = imp.load_source("made_up_name", "a15800")
>
> >>> module.myVar
>
> 'hello'
>
> >>> "made_up_name" in sys.modules
>
> True
>
> >>> module
>
> <module 'made_up_name' from 'a15800c'>
Thanks Peter Otten, that worked. I was not able to understand the documentation for imp.load_source correctly. Thanks so much!
More information about the Python-list
mailing list