到目前为止,我只在 REPL 中尝试过这个,在任何块之外。也许也可以让它在其他地方发挥作用。
我把它放在我的 python 启动文件中:
import sys, traceback
def bareWordsHandler(type_, value, traceback_):
if isinstance(value, SyntaxError):
import traceback
# You can probably modify this next line so that it'll work within blocks, as well as outside them:
bareWords = traceback.format_exception(type_, value, traceback_)[1].split()
# At this point we have the raw string that was entered.
# Use whatever logic you want on it to decide what to do.
if bareWords[0] == 'Awesome':
print(' '.join(bareWords[1:]).upper() + '!')
return
bareWordsHandler.originalExceptHookFunction(type_, value, traceback_)
bareWordsHandler.originalExceptHookFunction = sys.excepthook
sys.excepthook = bareWordsHandler
快速 REPL 会话演示后记:
>>> Awesome bare words
BARE WORDS!
负责任地使用。
编辑:这是一个更有用的例子。我添加了一个run
关键词。
if bareWords[0] == 'from' and bareWords[2] == 'run':
atPrompt.autoRun = ['from ' + bareWords[1] + ' import ' + bareWords[3].split('(')[0],
' '.join(bareWords[3:])]
return
atPrompt.autoRun
是一个变量列表,当显示我的提示时,将自动检查并反馈这些变量。因此,例如,我可以这样做:
>>> from loadBalanceTester run loadBalancerTest(runJar = False)
这被解释为:
from loadBalancerTest import loadBalancerTest
loadBalancerTest(runJar = False)
它有点像宏 - 我想做这种事情是很常见的,所以我决定添加一个关键字,让我可以用更少的击键来完成它。