import file without .py into another module

Tim Chase python.list at tim.thechases.com
Tue Jan 21 10:36:20 EST 2014


On 2014-01-21 07:13, kevinbercaw at gmail.com wrote:
>On Tuesday, January 21, 2014 10:06:16 AM UTC-5, MRAB wrote:
>>      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'

Check what you're passing for fileName/FilePath:

 >>> import imp
 >>> with open('demo.txt', 'wb') as f:
 ...     f.write('x = 42\ny = "hello"\n')
 ... 
 >>> d = imp.load_source('SomeName', 'demo.txt')
 >>> dir(d)
 ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
 'x', 'y']
 >>> d.x
 42
 >>> d.y
 'hello'
 >>> d.__name__
 'SomeName'

-tkc







More information about the Python-list mailing list