2016-08-09 7 views
3

私は、システムのクリップボードにコピーされた数式を検出し、評価し、貼り付ける準備ができているクリップボードにコピーをコピーする "コピーペースト計算機"を開発中です。しかし、コードではeval()関数を使用していますが、ユーザーが通常何をコピーしているかを知っていることを考えると、私は大変心配していません。つまり、計算をハンディキャップ(例えば、乗算や指数を計算する能力を取り除くなど)をせずに、より良い方法を見つけたいと思っています。Python3でeval()を使用しない数式を評価する

ここに私のコードの重要な部分です:

#! python3 
import pyperclip, time 

parsedict = {"×": "*", 
      "÷": "/", 
      "^": "**"} # Get rid of anything that cannot be evaluated 

def stringparse(string): # Remove whitespace and replace unevaluateable objects 
    a = string 
    a = a.replace(" ", "") 
    for i in a: 
     if i in parsedict.keys(): 
      a = a.replace(i, parsedict[i]) 
    print(a) 
    return a 

def calculate(string): 
    parsed = stringparse(string) 
    ans = eval(parsed) # EVIL!!! 
    print(ans) 
    pyperclip.copy(str(ans)) 

def validcheck(string): # Check if the copied item is a math expression 
    proof = 0 
    for i in mathproof: 
     if i in string: 
      proof += 1 
     elif "http" in string: #TODO: Create a better way of passing non-math copies 
      proof = 0 
      break 
    if proof != 0: 
     calculate(string) 

def init(): # Ensure previous copies have no effect 
    current = pyperclip.paste() 
    new = current 
    main(current, new) 

def main(current, new): 
    while True: 
     new = pyperclip.paste() 
     if new != current: 
      validcheck(new) 
      current = new 
      pass 
     else: 
      time.sleep(1.0) 
      pass 

if __name__ == "__main__": 
    init() 

Q:私は答えを計算する代わりにeval()をどう使うべきか?

答えて

5

あなたはast.parse使用する必要があります。

import ast 

try: 
    tree = ast.parse(expression, mode='eval') 
except SyntaxError: 
    return # not a Python expression 
if not all(isinstance(node, (ast.Expression, 
     ast.UnaryOp, ast.unaryop, 
     ast.BinOp, ast.operator, 
     ast.Num)) for node in ast.walk(tree)): 
    return # not a mathematical expression (numbers and operators) 
result = eval(compile(tree, filename='', mode='eval')) 

注簡略化のために、これはすべての単項演算子(+-~not)だけでなく、算術演算とビット単位のバイナリ演算子(+-を可能にすることを、 *,/,%,//**,<<,>>,&,|,^)、論理演算子または比較演算子は使用できません。許可された演算子を絞り込んだり展開したりするのは簡単です。

関連する問題