0

I would like to find an efficient and quick way to load the values of a list of global variables from a C header file into Python. For instance, suppose I have the file header.h:

/* comments */
int param_nx=2049; // comment
int param_ny=2049; // comment
double param_dt=0.01; // comment

Is there an easy way to read this file with Python, skip the comments, and define the corresponding variables there? I do not mind using the same variable name.

Davide
  • 83
  • 1
  • 1
  • 4
  • You can split on lines not starting with / and take the second element stripping the `;` but `int param_nx =2049;` would break that logic and a lot of other assignments – Padraic Cunningham Jun 18 '15 at 11:43
  • 1
    see this answer: http://stackoverflow.com/questions/15293604/import-constants-from-h-file-into-python?answertab=active#tab-top – Pramod Jun 18 '15 at 11:44

1 Answers1

0

Try this.

import re

r = re.compile("(double|int) ([a-zA-Z_]+)=([0-9\.]+)")

header = """/* comments */
int param_nx=2049; // comment
int param_ny=2049; // comment
double param_dt=0.01; // comment"""

params = {}

for line in header.split("\n"):
    m = r.search(line.strip())
    if m:
        if m.group(1) == "int":
            params[m.group(2)] = int(m.group(3))
        elif m.group(1) == "double":
            params[m.group(2)] = float(m.group(3))
print(params)

Output:

{'param_dt': 0.01, 'param_nx': 2049, 'param_ny': 2049}
  • Thanks Tichodroma, however I guess that your solution misses something. Where shall I put the information regarding the input file (in my case header.h)? – Davide Jun 18 '15 at 12:02
  • I've edited my answer. You can of course change this to read from a file. –  Jun 18 '15 at 12:04
  • Tichodroma, how can I actually use the value stored in params? For instance, is there a way to force Python doing "param_dt=0.01", that is define a variable param_dt and assign the value 0.01? Of course this should be iterated over all object contained in params. This might be a very elementary question but I am new to Python! – Davide Jun 19 '15 at 12:35
  • See https://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop The general advise is not to do this. Use a dictionary. –  Jun 19 '15 at 12:43