您好我正在嘗試在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