gpt4 book ai didi

Python 评估 : What's wrong with this code?

转载 作者:行者123 更新时间:2023-11-28 19:31:38 25 4
gpt4 key购买 nike

我正在尝试编写一个非常简单的 Python 实用程序供个人使用,它计算文本文件中命令行指定谓词为真的行数。这是代码:

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,所以我不知道它有什么怪癖,如果有的话)。请告诉我如何解决此问题以使其正常工作。

最佳答案

尝试使用 exec 而不是 eval。解释了两者之间的区别here

关于Python 评估 : What's wrong with this code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1456760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com