Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #64424

Re: import file without .py into another module

From Peter Otten <__peter__@web.de>
Subject Re: import file without .py into another module
Date 2014-01-21 16:40 +0100
Organization None
References <6c68b312-4979-454f-b483-b4a39c64196b@googlegroups.com> <mailman.5786.1390316784.18130.python-list@python.org> <022c00a5-87ee-4b2a-a6f6-e23c8bda1e12@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.5788.1390318785.18130.python-list@python.org> (permalink)

Show all headers | View raw


kevinbercaw@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'>

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

import file without .py into another module kevinbercaw@gmail.com - 2014-01-21 06:44 -0800
  Re: import file without .py into another module MRAB <python@mrabarnett.plus.com> - 2014-01-21 15:06 +0000
    Re: import file without .py into another module kevinbercaw@gmail.com - 2014-01-21 07:13 -0800
      Re: import file without .py into another module Tim Chase <python.list@tim.thechases.com> - 2014-01-21 09:36 -0600
      Re: import file without .py into another module Peter Otten <__peter__@web.de> - 2014-01-21 16:40 +0100
        Re: import file without .py into another module kevinbercaw@gmail.com - 2014-01-21 07:50 -0800
          Re: import file without .py into another module Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-01-21 18:10 +0000
  Re: import file without .py into another module kevinbercaw@gmail.com - 2014-01-21 07:27 -0800

csiph-web