import file without .py into another module

kevinbercaw at gmail.com kevinbercaw at gmail.com
Tue Jan 21 10:13:59 EST 2014


On Tuesday, January 21, 2014 10:06:16 AM UTC-5, MRAB wrote:
> On 2014-01-21 14:44,  wrote:
> 
> > I have a python script that accepts two arguments:
> 
> > sys.argv[1] is the full directory path to a config script.  The script is python but does not have a .py extension!
> 
> > sys.argv[2] is the file name of the config script
> 
> >
> 
> > For example:
> 
> > mainScript.py ./ a15800
> 
> >
> 
> >
> 
> > The config script sets variables that I want to be able to use in the main script.
> 
> >
> 
> > *** contents of "a15800": ***
> 
> > myVar = "hello"
> 
> >
> 
> > *** contents of "mainScript.py": ***
> 
> > def printVars(configModuleName):
> 
> >      myVarName = ("%s.myVar" % configModuleName)
> 
> >      print "myVarName = %s" % myVarName
> 
> >      myVarValue = eval(myVarName)
> 
> >      print "myVarValue = %s" % myVarValue
> 
> >
> 
> >
> 
> > if __name__ == '__main__':
> 
> >      import sys
> 
> >      import imp
> 
> >      filePath = sys.argv[1]
> 
> >      fileName = sys.argv[2]
> 
> >      configModuleObject = imp.load_source(fileName, filePath)
> 
> >      configModuleName = configModuleObject.__name__
> 
> >      print "configModuleName = %s" % configModuleName
> 
> >      printVars(configModuleName)
> 
> >
> 
> > *** Output: ***
> 
> >>mainScript.py ./ a15800
> 
> > configModuleName = a15800
> 
> > myVarName = a15800.myVar
> 
> > Traceback (most recent call last):
> 
> >    File "mainScript.py", line 27, in <module>
> 
> >      printVars(configModuleName)
> 
> >    File "mainScript.py", line 15, in printVars
> 
> >      myVarValue = eval(myVarName)
> 
> >    File "<string>", line 1, in <module>
> 
> > NameError: name 'a15800' is not defined
> 
> >
> 
> > *** Question: ***
> 
> > 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'



More information about the Python-list mailing list