简体   繁体   中英

Why won't eval() run this line in python?

At first I was getting a syntax error with this code:

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

I thought perhaps I messed something up so I tried to start barebones (literally just reading in one image) from:

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)') 

but I'm still getting a syntax error. What the code is reading is

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

which I know works because I had done it just a couple of weeks ago, so I don't know if this is an issue fundamentally with eval? My knowledge on it isn't great and so I'm not sure if what I input into it doesn't work. The error code is as follows:

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

You cannot eval assignments, eval is basically just for evaluating things normally found on the right of an assignment statement.

You probably should be using exec for this, provided you understand and mitigate the risks. For example, see the following code, loosely based on yours:

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')

The first call, exec , will work, and set the global A1 . The second will also work because you're not attempting an assignment. The third will fail:

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

Just keep in mind you can't use exec to set local variables inside a function, see here for details but it's basically caused by the fact that the locals dictionary passed by default to exec is a copy of the actual locals (a dictionary built for heavily optimised internal structures).

However, you can pass your own dictionary to exec to be treated as the locals and then use that to get at the variables that were set - there's just no easy way (or any way, really) to echo that back to the actual locals.

The following code shows how to do this:

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]}'")

And the output is:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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