import file without .py into another module
kevinbercaw at gmail.com
kevinbercaw at gmail.com
Tue Jan 21 10:27:50 EST 2014
On Tuesday, January 21, 2014 9:44:13 AM UTC-5, kevin... at gmail.com 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.
FYI - more info from interactive session, query configModuleObject and configModuleName using imp.find_module:
>>> imp.find_module("configModuleObject")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named configModuleObject
>>> imp.find_module("a15800")
(<open file 'a15800.pyc', mode 'rb' at 0x2b503b72d288>, 'a15800.pyc', ('.pyc', 'rb', 2))
>>> imp.find_module(configModuleName)
(<open file 'a15800.pyc', mode 'rb' at 0x2b503b72d300>, 'a15800.pyc', ('.pyc', 'rb', 2))
More information about the Python-list
mailing list