0

If I use the exec statement for a for statement, an error occurs.

My code:

exec 'for i in A_'+aws_n+'_DATI[:]:'
exec '    a_'+aws_n+'_tt += {datetime.datetime.strptime(A_'+aws_n+'_DATI[n], "%Y%m%d%H%M")}'
exec '    n  += 1'

Result:

**Traceback (most recent call last):
  File "aws_merge.py", line 140, in <module>
    exec 'for i in A_'+aws_n+'_DATI[:]:'
  File "<string>", line 1
    for i in A_156_DATI[:]:
                          ^
SyntaxError: unexpected EOF while parsing**

However, in the above code, if you remove the exec statement and manually process the variable aws_n, it will run without any problems.

for i in A_156_DATI[:]:
    print n
    n  += 1

Why is not it running?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
  • There's almost never a good reason to use `exec`. And using it to dynamically create variable names, like your `A_156_DATI`, is _definitely **not**_ a good reason. But if you wish to learn more about `exec` (and `eval`), please see [this excellent answer](https://stackoverflow.com/a/29456463/4014959). – PM 2Ring Jun 13 '17 at 04:46
  • Possible duplicate of [What's the difference between eval, exec, and compile in Python?](https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python) – DYZ Jun 13 '17 at 04:57

1 Answers1

2

First, do not ever use exec(). It is completely unnecessary and dangerous. Second, exec() executes a complete statement. for i in A_156_DATI[:]: is not a complete statement, but a part of a loop statement. If you really want to do a silly thing, put all lines of the loop together:

exec 'for i in A_'+aws_n+'_DATI[:]: a_'+aws_n+'_tt += ...; n  += 1'

For your reference, [:] in your case is not needed.

DYZ
  • 55,249
  • 10
  • 64
  • 93