0

I want to execute code read from an Excel workbook. For some reason the following code does not actually evaluate, however.

import win32com.client
import os

excel = win32com.client.DispatchEx('Excel.Application')
local_dir = os.getcwd()
book = excel.Workbooks.Open(local_dir+'\\Condition.xlsx', True)
sheet = book.Sheets('Sheet1')

condition = sheet.Cells(1,3).Value

print condition
print eval(condition)

excel.Workbooks.Close()

If the cell in question contains "1+2", the above code just prints out "1+2", not "3". If I replace "condition" with "1+2", it evaluates correctly. Any idea why this isn't working?

PProteus
  • 549
  • 1
  • 10
  • 23
  • 2
    does the string itself contain quotes? That is likely the problem... Try `eval(condition.strip('"')` – juanpa.arrivillaga Apr 10 '17 at 17:28
  • 1
    Your cell contains the string `"1+2"`, quotes included, which evaluates as this string. And beware of `eval`... – Thierry Lathuille Apr 10 '17 at 17:29
  • Yes, that was the problem. Thanks! I'm not sure how else to do what I need to do other than use eval. I need to enable the user to define a logic expression that has no pre-defined form or structure, and it will require API calls, etc. – PProteus Apr 10 '17 at 17:34

1 Answers1

1

I don't recommend you using eval() because it can be very dangerous and harmful to your code's security.

Instead of that i recommend you using literal_eval from ast module:

from ast import literal_eval as eval
# work to do ...

So, an easy fix to your code in order to handle strings with quotes like "1+3" and others, you can do something like this:

from ast import literal_eval as eval
# your actual code
# ...
print(eval(condition.replace('"', '')))
# Or
# print(eval(condition.strip('"')))

Edit:

The difference between eval() and literal_eval():

  • eval(my_string_or_input): evaluates the code (string/input/raw_input) as soon as the function is called without checking if the code in the argument is safe or not.
  • literal_eval(my_string_or_input): will raise an exception if the string/input/raw_input in the argument isn't a valid Python code. So, it will not be excecuted if there is an unsafe code.

You can check this question/answers in stackoverflow for more explanations.

Community
  • 1
  • 1
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
  • 1
    Can you explain the difference between eval and ast.literal_eval? – PProteus Apr 10 '17 at 17:45
  • 1
    There's more to it than that. literal_eval only allows a certain subset of python syntax, and it does not allow you to grab global and local dictionaries from the evaluation (a feature I actually need). – PProteus Apr 10 '17 at 18:06
  • So, be aware while using `eval()`. You know what you're facing :-) – Chiheb Nexus Apr 10 '17 at 18:08