Python Eval: What's Wrong With This Code?

I am trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which the predicate given on 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 with 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 (although I've never used Python eval before, so I don't know what its quirks, if any, are). Please tell me how can I fix this to make it work.

+2


source to share


5 answers


#!/usr/bin/env python
import fileinput, sys

pred = eval('lambda line: ' + sys.argv[1])
print sum(1 for line in fileinput.input(sys.argv[2:]) if pred(line))

      



Usage: pywc.py predicate [FILE]...


Print the number of lines satisfying predicate

for the given FILE

(s).
Without FILE

, or when FILE is, read the standard input.

+3


source


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



+11


source


try:

for line in handle:
  result += 1 if eval(pred) else 0

      

+5


source


The python eval () function evaluates expressions, not expressions. Try replacing the eval () line with this:

result += eval(pred + " else 0")

      

+2


source


Indeed, you are looking for a compilation function:

>> a = compile("toAdd = 1 if int('0') == 0 else 0", 'tmp2.py', 'exec')
>>> eval(a)
>>> toAdd
1

      

eval is only for expressions ... compiles, compiles a sequence of instructions into a code block, which can then be evaluated.

0


source







All Articles