2016-06-01 177 views
0

多年來我一直使用AnalogX PCalc作爲我的計算器,用於包絡交互計算,其中整數數學非常重要,靈活的基礎輸入和輸出非常重要。例如,當使用定點數時,通常既不是一個十進制數也不是十六進制數的視圖有助於解決問題。它還內置了漂亮的C數學函數,以及返回整數的字符串函數。缺點是顯而易見的,因爲它僅限於功能集和Windows。使用Python交互式作爲編程計算器

我在想Python交互會是一個更好的計算器,而且一般情況下,如果你只關心一個基礎,並且不關心整數數學模擬器。但至少對於這兩個限制來說,這並不是很好。因此,至少可以讓Python交互式地打印多個基地的整數,或者基數10以外的其他基地,而不必每次都預先加上「hex()」?

+0

難道你不能只是創建一個具有輸出所有所需格式數字的函數的小模塊嗎? –

+1

檢出十進制模塊,十進制類型的子類可以很容易地以首選格式輸出,並且在劃分時不會遇到浮點精度問題。 – Perkins

回答

1

Python標準庫提供了codecodeop模塊,因此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參數中傳遞。

+0

這是一個很好的開始。這絕對可以擴展到與多基輸出功能接近,同時在功能上更勝一籌。由於鉤子安裝起來並不是非常簡單,因此只需要在跑步機器上放置腳本。 –