0

I have an python application which reads the python scripts and runs it and returns the values:

main.py

     def Exec(id): 
        try:
           connection = mysql.connector.connect(host='localhost',
                                           user='root',
                                           password='',
                                           database='mydb')
      # Fetch the python script from pythontbl table
      sql_select_Query = "SELECT python FROM mydb.pythontbl WHERE id={}".format(id)
      cursor = connection.cursor()
      cursor.execute(sql_select_Query)
      # get all records
      script = cursor.fetchall()
     
      # execute the python script with arguments
      ??
      # return value should be saved in out
      out= ???
      print("output",out) ??

     except mysql.connector.Error as e:
      print("Error reading data from MySQL table", e)
     finally:
      if connection.is_connected():
        connection.close()
        cursor.close()
        print("MySQL connection is closed")

how can I execute the python script which I fetched from my main and sending the arguments to script and get back the result ? I can not use import script.py as I am fetching the script through my main.py

sama
  • 333
  • 2
  • 11
  • please refer https://stackoverflow.com/questions/2349991/how-do-i-import-other-python-files – Jaydeep Devda Nov 23 '22 at 11:07
  • What kind of arguments are you sending and how is the python consuming them? – CumminUp07 Nov 23 '22 at 11:07
  • 2 ways, either import your other python script's functions and call them, or use the `subprocess` module to call the python script and get the results. Method 1 is way better, recommended and the standard – Manish Dash Nov 23 '22 at 11:08
  • I can not use import as the script is fetched through main.py and it is not pre created. – sama Nov 23 '22 at 11:18
  • If what you retrieve from the DB is the python code itself, then you'll want to pass it as argument to [`exec`](https://docs.python.org/3/library/functions.html#exec). As to how to retrieve the output you might consider passing in some locals or globals to `exec` or finding out how to obtain the stdout of your program from your main program – EDG956 Nov 23 '22 at 11:38
  • The problem is that I can not retrieve the output unless I use import script which is pre prepared file. as exec os.systtem ,... all return only success or not success not the return value of the script – sama Nov 23 '22 at 11:42

1 Answers1

0

create another file name fetchscript.py and in this file create the connection and fetch the script from your table , call fetchscript.py from main.py and then import pythonscript and call the desired function from pythonscript.py

sama
  • 333
  • 2
  • 11