您好我正在尝试在Python中实现条件编译类似于this in C,我已经看到this thread和this thread。Python中的条件编译
但是this不起作用。我对python比较陌生,我们该如何解决这个问题?
您好我正在尝试在Python中实现条件编译类似于this in C,我已经看到this thread和this thread。Python中的条件编译
但是this不起作用。我对python比较陌生,我们该如何解决这个问题?
看起来您正在尝试使用此功能向网上裁判提交解决方案。对于海湾合作委员会,法官机器提供了一个参数-D ONLINE_JUDGE
。这与您的代码具有相同的效果:
#define ONLINE_JUDGE
Python没有预处理器。因此,在调用解释器时,无论是在代码中还是从命令行中定义宏(与C中相同),都没有办法。所以,我认为网上裁判不太可能为Python提供类似的选项。但它可能提供了一些命令行参数,您可以通过sys.argv[1:]
使用该参数。在网上评判中检查用于调用Python的命令(必须在他们的网站上提及)。
您需要定义ONLINE_JUDGE变量 - 这是一个“if”,而不是“ifdef”。
ONLINE_JUDGE = 0
if ONLINE_JUDGE:
import math
不,这个ONLINE_JUDGE在网上评判中被定义为true,那么我猜这是行不通的。 – Quixotic 2011-03-14 06:34:31
@Tretwick:这个评论没有意义。名称不会简单地“出现”;要么是他们定义的,要么是进口的。 – 2011-03-14 06:37:57
@Ignacio Vazquez-Abrams:我说名字被定义为真正的在线评委仔细阅读我的评论。原始网站似乎下来检查了这[缓存](http://webcache.googleusercontent.com/search?q=缓存:xxdOhpKUYYQJ:acm.tju.edu.cn/toj/faq.html+%23define+ONLINE_JUDGE&cd=5&hl=zh-CN&ct=clnk&gl=in&source=www.google.co.in) – Quixotic 2011-03-14 06:43:28
codeforces.com(linked in your comment)调用Python脚本为python -O %s
。您可以通过__debug__
在脚本中检测到它。比较:
$ python -c 'print __debug__'
True
和
$ python -O -c 'print __debug__'
False
所以,你可以在你的脚本写:
ONLINE_JUDGE = not __debug__
# ...
if ONLINE_JUDGE:
pass # here goes online judge specific stuff
也可在PYPI (Python Package Index)发现所以可以使用pip加载。
你具体的例子看起来是这样的:
from pypreprocessor import pypreprocessor
pypreprocessor.parse()
#define onlinejudge
#ifdef onlinejudge
import math
#endif
为了增加通过命令行来定义也很容易实现:
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
这里的输出应该生产什么...
'python prog.py mode1':
这个脚本在模式1
'蟒蛇prog.py模式2' 运行:
这个脚本在运行模式2
“蟒蛇编。PY模式1模式2' :
这个脚本在模式1 运行此脚本在运行模式2
'蟒蛇prog.py':
没有模式指定
SideNote:pypreprocessor支持python2x和python3k。
免责声明:我pypreprocessor
有点太沉重了,我的口味的作者。这个怎么样:
import sys
try: fin = open('Problem.in')
except: fin = sys.stdin
通用和真正方便本身。二合一。
我检查了[这里](http://www.codeforces.com/blog/entry/79),所以我想我必须自己做安排。谢谢。 – Quixotic 2011-03-14 06:44:51
@Tretwick Marian:Ah CodeForces :)。你可以请求他们在他们的命令行中添加一个参数。他们非常乐于接受反馈。 – MAK 2011-03-14 06:52:40
这不仅仅是codeforces,我想这个标准对于像spoj和sgu这样的其他评判来说是非常相似的,但是我更喜欢在spoj中使用:-) – Quixotic 2011-03-14 06:59:11