0

I'm trying to fetch values from a PSQL table to dynamically trigger methods or assign variables using Python exec().

Say we have a postgres table like so :

id |          commands           | flag_activ
---+-----------------------------+------------
1  | keyword = 'miscellaneous'   | TRUE
2  | keyword = 'multifarious'    | FALSE
3  | print('PRINT FOR DEMO')     | FALSE

My code :

conn = connect_db(host,database,user,password)
cur = conn.cursor()            
query = 'SELECT commands FROM table WHERE flag_activ = TRUE'             
cur.execute(query)   
res = cur.fetchone()[0]
             

At this point, if I print(res), I get the output :

> keyword='miscellaneous'

which is the command that I'm trying to pass to the exec() method, in order to create a variable called keyword.

PROBLEM : when I call exec(res), then I print(keyword)I get this error:

> NameError: name 'keyword' is not defined

Expected output:

> miscellaneous

Why is the variable assignment not being taken into account here ? What am I missing ?

What I have tried :

  1. Debugging in a Python shell :

    >>> print(keyword)
    NameError: name 'keyword' is not defined
    >>> res = 'keyword = "miscellaneous"'
    >>> exec(res)
    >>> print(keyword)
    miscellaneous
    

This works as expected.

  1. Passing a method instead of a variable assignment. In the case of row id n°3 :

    ...
    >>> query = 'SELECT commands FROM table WHERE id = 3'
    >>> cur.execute(query)
    >>> res = cur.fetchone()[0]
    >>> exec(res)
    PRINT FOR DEMO
    

This also works as expected.

  1. Declaring keyword as an empty string beforehand : the exec() method does not reassign the variable to the expected value miscellaneous.

Would appreciate any help. Thanks !

Barmar
  • 741,623
  • 53
  • 500
  • 612
junsuzuki
  • 100
  • 7

0 Answers0