为什么eval()不在python中运行这一行?

2024-06-11 18:15:44 发布

您现在位置:Python中文网/ 问答频道 /正文

起初,我在代码中遇到语法错误:

eval('A'+str(x)+' = np.flip(cv2.imread(r"'+str(path)+'\\'+str(image[x-firstImage])+'", cv2.IMREAD_UNCHANGED),1)')

我想可能是我弄糟了什么,所以我试着从以下几个方面开始裸骨阅读(字面上只是在一张图片中阅读):

import numpy as np
import cv2

x = 1

#Number of pixels in img
column = 500
row = 200

A1 = np.zeros((row,column)) 

path = r'C:\Users\Boyon\Desktop\PhotoFile'
image = 'photo01.tif'

eval('A'+str(x)+' = cv2.imread(r"'+str(path)+'\\'+str(image)+'",cv2.IMREAD_UNCHANGED)') 

但我仍然得到一个语法错误。代码正在读取的是

A1 = cv2.imread(r"C:\Users\Boyon\Desktop\PhotoFile\photo01.tif",cv2.IMREAD_UNCHANGED)

我知道这是有效的,因为我几周前刚刚做过,所以我不知道这是否是eval的一个根本问题?我在这方面的知识不是很好,所以我不确定我输入的内容是否有效。 错误代码如下所示:

  File "<string>", line 1
    A1 = cv2.imread(r"C:\Users\Boyon\Desktop\PhotoFile\photo01.tif")
       ^
SyntaxError: invalid syntax

Tags: pathimagea1evalnpcv2usersdesktop
1条回答
网友
1楼 · 发布于 2024-06-11 18:15:44

您不能eval赋值,eval基本上只是用于评估通常在赋值语句的右侧上找到的内容

如果您了解并减轻风险,您可能应该为此使用exec。例如,请参阅以下代码,大致以您的代码为基础:

path = r'C:\Users\Boyon\Desktop\PhotoFile'
image = 'photo01.tif'

x = 1
exec('A'+str(x)+' = r"'+str(path)+'\\'+str(image)+'"')
print('EXEC', A1, '\n')

x = 2
A1 = eval(r"str(path)+'\\'+str(image)+str(x)")
print('EVAL1', A1, '\n')

x = 3
eval('A'+str(x)+' = r"'+str(path)+'\\'+str(image)+'"')
print('EVAL2', A1, '\n')

第一个调用exec将起作用,并设置全局A1。第二种方法也可以,因为您没有尝试分配任务。第三个将失败:

EXEC C:\Users\Boyon\Desktop\PhotoFile\photo01.tif

EVAL1 C:\Users\Boyon\Desktop\PhotoFile\photo01.tif2

Traceback (most recent call last):
  File "testprog.py", line 13, in <module>
    eval('A'+str(x)+' = r"'+str(path)+'\\'+str(image)+'"')
  File "<string>", line 1
    A3 = r"C:\Users\Boyon\Desktop\PhotoFile\photo01.tif"
       ^
SyntaxError: invalid syntax

请记住,您不能使用exec在函数中设置局部变量,有关详细信息,请参见here,但这基本上是由于默认情况下传递给execlocals字典是实际局部变量(为高度优化的内部结构构建的字典)的副本

但是,您可以将自己的词典传递给exec作为局部变量处理,然后使用它来获取设置的变量-没有简单的方法(或者说任何方法)将其回传给实际的局部变量

以下代码显示了如何执行此操作:

path = '/tmp/PhotoFile'
image = 'photo01.tif'

# Construct dictionary to take "locals".

mydict = {}
for i in range(10):
    exec(f"a{i} = '{path}/photo{9-i:02d}'", globals(), mydict)

# Show how to get at them.

for key in mydict:
    print(f"My dictionary: variable '{key}' is '{mydict[key]}'")

输出为:

My dictionary: variable 'a0' is '/tmp/PhotoFile/photo09'
My dictionary: variable 'a1' is '/tmp/PhotoFile/photo08'
My dictionary: variable 'a2' is '/tmp/PhotoFile/photo07'
My dictionary: variable 'a3' is '/tmp/PhotoFile/photo06'
My dictionary: variable 'a4' is '/tmp/PhotoFile/photo05'
My dictionary: variable 'a5' is '/tmp/PhotoFile/photo04'
My dictionary: variable 'a6' is '/tmp/PhotoFile/photo03'
My dictionary: variable 'a7' is '/tmp/PhotoFile/photo02'
My dictionary: variable 'a8' is '/tmp/PhotoFile/photo01'
My dictionary: variable 'a9' is '/tmp/PhotoFile/photo00'

相关问题 更多 >