Python 标准库提供了code 和codeop 模块,因此REPL 的功能也可以在其他程序中使用。
例如,这里是一个示例 Python 文件,它扩展了标准库类以提供一个新的交互式控制台,可以将整数结果转换为其他基数(目前支持基数 2 和 16,但添加其他基数应该很容易)。使用了几行额外的代码来支持 Python 2 和 3。
#!/usr/bin/env python
from __future__ import print_function
import sys
import code
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class NumericConsole(code.InteractiveConsole):
def __init__(self, *args, **kwargs):
code.InteractiveConsole.__init__(self, *args, **kwargs)
self.base = 10
def runcode(self, code_to_run):
return_val, output = self._call_and_capture_output(code.InteractiveConsole.runcode, self, code_to_run)
try:
output = self._to_target_base(output) + '\n'
except ValueError:
pass
print(output, end='')
return return_val
def _to_target_base(self, value):
# this can be extended to support more bases other than 2 or 16
as_int = int(value.strip())
number_to_base_funcs = {16: hex, 2: bin}
return number_to_base_funcs.get(self.base, str)(as_int)
def _call_and_capture_output(self, func, *args, **kwargs):
output_buffer = StringIO()
stdout = sys.stdout
try:
sys.stdout = output_buffer
func_return = func(*args, **kwargs)
finally:
sys.stdout = stdout
return (func_return, output_buffer.getvalue())
def interact(base=10):
console = NumericConsole()
console.base = base
console.interact()
if __name__ == '__main__':
base = len(sys.argv) > 1 and int(sys.argv[1]) or 10
interact(base)
现在您可以运行此脚本并将所需的基数作为第一个 CLI 参数传递:
$ python <this_script> 16
如果任何表达式的结果是整数,它将以十六进制格式打印。
当然可以添加更多的基数(假设您将有一个函数将十进制值转换为该基数),并且有更漂亮的方法来传递 CLI 参数。