开发者

Mimic C preprocessor with Python/Ruby?

开发者 https://www.devze.com 2022-12-27 12:31 出处:网络
I need to mimic the preprocessor feature of C with Python. If I want to run the debug release, I use as follows with C

I need to mimic the preprocessor feature of C with Python.

If I want to run the debug release, I use as follows with C

#ifdef DEBUG
printf(...)
#endif

I just use -DDEBUG or similar开发者_开发问答 to trigger it on or off.

What 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 the script files in a project?


You usually use the python logging functionality in this use-case. That is configured in configuration files, and you can set the output levels. Very close in usage to java log4j, if you're familiar with that.


You can almost use the actual C preprocessor. If you rename your file to end in .c, you can then do this: gcc -w -E input/file.py.c -o output/file.py.

The main issue seems to be with comments. The preprocessor will complains about python comment lines being invalid preprocessor directives. You can remedy this by using C++ comments (// comment).

Or, a better idea would be to just write your own simple preprocessor. If you only need #define functionality, you're just talking about a doing a search and replace on 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

That way your print statements don't do anything if you're not in debug mode.


Use pypreprocessor

The latest release can also be accessed through the PYPI

Here's the basic usage:

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. C style preprocessor conditional compilation implemented in python.

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

Disclaimer: I'm the author of pypreprocessor.

0

精彩评论

暂无评论...
验证码 换一张
取 消