Mimic C preprocessor with Python / Ruby?

I need to emulate a C preprocessor function from Python.

If I want to run the debug version I use like this: C

#ifdef DEBUG
printf(...)
#endif

      

I just use -DDEBUG or similar to turn it on or off.

Which method can I use for Python / Ruby? I mean, what should I do to control the behavior of python / ruby ​​scripts in such a way that I can change a variable that affects all script files in the project?

+2


a source to share


3 answers


You can use the actual preprocessor C. If you rename a file in the end .c

, you can do this: gcc -w -E input/file.py.c -o output/file.py

.

The main problem seems to be with the comments. The preprocessor will complain that python comment lines are invalid preprocessor directives. You can fix this using C ++ comments ( // comment

).

Or it would be better to write your own simple preprocessor. If you only want a function #define

, you are just talking about doing find and replace in your file.



Another solution would be something like this:

def nothing(*args):
    pass

def print_debug(msg):
    print msg

if not DEBUG: 
    print_debug = nothing

      

Thus, your print instructions do nothing unless you are in debug mode.

+2


a source


You usually use python logging function in this use case. This is set up in the config files and you can set the output levels. Very close to being used in java log4j if you are familiar with it.



+5


a source


Use pypreprocessor

The latest version is also available through PYPI

Here's the main use:

from pypreprocessor import pypreprocessor

pypreprocessor.parse()

#define debug

#ifdef debug
print('The source is in debug mode')
#else
print('The source is not in debug mode')
#endif

      

There you go. Conditional C style preprocessor compilation implemented in python.

SideNote: The module is compatible with both python2x and python3k.

Disclaimer: I am the author of pypreprocessor.

+2


a source







All Articles