Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Eval: What's wrong with this code?

I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:

import sys

pred = sys.argv[2]
if sys.argv[1] == "stdin" :
    handle = sys.stdin
else :
    handle = open(sys.argv[1])
result = 0
for line in handle :
    eval('result += 1 if ' + pred + ' else 0')
print result

When I run it using python count.py myFile.txt "int(line) == 0", I get the following error:

  File "c:/pycode/count.py", line 10, in <module>
    eval('toAdd = 1 if ' + pred + ' else 0')
  File "<string>", line 1
    toAdd = 1 if int(line) == 0 else 0

This looks like perfectly valid Python code to me (though I've never used Python's eval before, so I don't know what its quirks, if any, are). Please tell me how I can fix this to make it work.

like image 873
dsimcha Avatar asked Dec 18 '25 02:12

dsimcha


2 Answers

Try using exec instead of eval. The difference between the 2 is explained here

like image 89
ennuikiller Avatar answered Dec 20 '25 19:12

ennuikiller


try:

for line in handle:
  result += 1 if eval(pred) else 0
like image 33
orip Avatar answered Dec 20 '25 17:12

orip