On 2014-01-21 14:44, kevinber...@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.
The line:
configModuleObject = imp.load_source(fileName, filePath)
imports the module and then binds it to the name configModuleObject,
therefore:
print configModuleObject.myVar
--
https://mail.python.org/mailman/listinfo/python-list