Python Eval:这段代码有什么问题?
我正在尝试编写一个非常简单的供个人使用的 Python 实用程序,用于计算文本文件中命令行指定的谓词为 true 的行数。这是代码:
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
当我使用 python count.py myFile.txt "int(line) == 0" 运行它时,我收到以下错误:
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
这对我来说看起来是完全有效的 Python 代码(尽管我以前从未使用过 Python 的 eval,所以我不知道它有什么怪癖(如果有的话)。请告诉我如何解决这个问题以使其正常工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试使用 exec 而不是 eval。 此处解释了两者之间的区别
Try using exec instead of eval. The difference between the 2 is explained here
尝试:
try:
用法:
pywc.py 谓词 [FILE]...
打印给定
FILE
满足谓词
的行数。没有
FILE
或 FILE 为 - 时,读取标准输入。Usage:
pywc.py predicate [FILE]...
Print number of lines that satisfy
predicate
for givenFILE
(s).With no
FILE
, or when FILE is -, read standard input.python eval() 函数计算表达式,而不是语句。尝试将 eval() 行替换为:
The python eval() function evaluates expressions, not statements. Try replacing the eval() line with:
实际上,您正在寻找compile 函数:
eval 仅适用于表达式...compile while 将语句序列编译成代码块,然后可以对其进行eval'ed。
Really, you are looking for the compile function:
eval is intended only for expressions... compile while compile sequence of statements into a codeblock that can then be eval'ed.