How to pass a string as a variable name assignment

I have an SDF data file that stores the names of variables and their values ​​in block format.

The values ​​aside varNameListare the names of the variables (lines), according to which the data block is inside the sdf file, and it can be accessed only by specifying these variable names.

I read the data file and variables using the following code in ipython

import sdf
import numpy as np
dataFile = sdf.read('0010.sdf')

varNameList = dir(dataFile)  
varSize = np.size(varNameList)  #gives the array size
vName = 'dataFile.'+np.str(varNameList[51])+'.data'

The outputs of the variable names are as follows:

In [71]:varNameList[51]
Derived_Number_Density_electron

In [72]:vName
'dataFile.Derived_Number_Density_electron.data'

Now I want to use this line on the right side of the job, for example.

electronDensity = dataFile.Derived_Number_Density_electron.data

If I write this line in a standard Python program, it reads the data and assigns it an electron density.

, dir(), . ,

electronDensity = dataFile.Derived_Number_Density_electron.data
+4
3

eval Python. :

>>> x = 123
>>> y = "x"
>>> z = eval(y)
>>> 
>>> print z
123

:

electronDensity = eval(vName)
+1

vars , . globals locals.

getattr :

vs = vName.split('.')
varname = vs.pop(0)
value = vars()[varname]
for v in vs:
   value = getattr(value, v)

electronDensity = value
0

Thanks for answers. I did the following and it worked. That way, even if I don’t know which vaiables created in each simulation run, my python-script post-processing will take care of dynamically generated variables during the simulation run.

path = '/home/ajit/run/data/0001.sdf'
datafile=sdf.read(path)
varNameList = dir(datafile)   #reads all the variable names
varNameSize = np.size(varNameList)
varName=[0 for i in range(varNameSize]
varData=[0 for i in range(varNameSize]

for i in range (0, varNameSize):
      varName[i] = 'q.'+np.str(varNameList[i])+'.data'
      varData[i] = eval(varName[i])        

Thanks again.

0
source

Source: https://habr.com/ru/post/1620244/


All Articles