2

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.

0

5 Answers 5

11

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

0
5

try:

for line in handle:
  result += 1 if eval(pred) else 0
3
#!/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 number of lines that satisfy predicate for given FILE(s).
With no FILE, or when FILE is -, read standard input.

2
  • This is excellent, a great improvement over the other versions in simplicity and efficiency. Sep 22, 2009 at 1:41
  • 1
    Thanks. This is a heck of a lot faster than the other versions, I guess because the interpreter parses and compiles the predicate O(1) instead of O(N) times.
    – dsimcha
    Sep 29, 2009 at 18:11
2

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

result += eval(pred + " else 0")
1
  • 1
    eval('int(line) == 0 else 0') produces SyntaxError.
    – jfs
    Sep 21, 2009 at 21:16
0

Really, you are looking for the compile function:

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

eval is intended only for expressions... compile while compile sequence of statements into a codeblock that can then be eval'ed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.