繁体   English   中英

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

[英]Why won't eval() run this line in 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

你不能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在 function 中设置局部变量,请参阅此处了解详细信息,但这基本上是由于默认情况下传递给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]}'")

而 output 是:

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM