开发者

Conditional compilation in python

Hi I am trying to implement c开发者_开发问答onditional compilation in python similar to this in C,I have seen this thread and this thread.

But this is not working. I am relatively new to python,how can we fix this ?


Looks like you are trying to use this to submit solutions to an online judge. For gcc, the judge machine supplies a paramater -D ONLINE_JUDGE. This has the same effect as having the following in your code:

#define ONLINE_JUDGE

Python does not have a preprocessor. So there is no way of defining a macro (in the same sense as in C) either within your code or from the command line when you invoke the interpreter. So, I think it is unlikely that the online judge provides a similar option for Python. But it might provide something as a command line argument that you might be able to use via sys.argv[1:]. Check the command used to invoke Python (must be mentioned somewhere on their website) at the online judge.


A bit too heavy for my taste. How about this one:

import sys
try: fin = open('Problem.in')
except: fin = sys.stdin

Universal and really convenient per se. Two in one.


You need to define the ONLINE_JUDGE variable - this is an "if", not really an "ifdef".

ONLINE_JUDGE = 0
if ONLINE_JUDGE:
    import math


codeforces.com (linked in your comment) invokes Python scripts as python -O %s. You can detect it in your script via __debug__. Compare:

$ python -c 'print __debug__'
True

and

$ python -O -c 'print __debug__'
False

So you could write in your script:

ONLINE_JUDGE = not __debug__
# ...
if ONLINE_JUDGE:
   pass # here goes online judge specific stuff


Use pypreprocessor

Which can also be found at the PYPI (Python Package Index) so it can be loaded using pip.

Your specific example would look something like:

from pypreprocessor import pypreprocessor
pypreprocessor.parse()

#define onlinejudge

#ifdef onlinejudge
import math
#endif

To adding a define via the command line is also easily accomplished:

import sys
from pypreprocessor import pypreprocessor

#exclude

# defined if 'mode' is found in the command line arguments
if 'mode1' in sys.argv:
    pypreprocessor.defines.append('mode1')

# defined if 'mode2' is found in the command line arguments
if 'mode2' in sys.argv:
    pypreprocessor.defines.append('mode2')

#endexclude

pypreprocessor.parse()

#ifdef mode1
print('this script is running in mode1')
#ifdef mode2
print('this script is running in mode2')
#else
print('no modes specified')
#endif

Here's what the outputs should produce...

'python prog.py mode1':

this script is running in mode1

'python prog.py mode2':

this script is running in mode2

'python prog.py mode1 mode2':

this script is running in mode1 this script is running in mode2

'python prog.py':

no modes specified

SideNote: pypreprocessor supports both python2x and python3k.

Disclaimer: I'm the author of pypreprocessor

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜