Running a SQL file from Python

I need to run a python sql file. The file is for mysql. I tried it this way:

from subprocess import Popen, PIPE
import sys


class ImportSql:
    def execImport(self, fileSql):
        try:
            with open(fileSql, 'r') as fileInput:
                proc = Popen(["mysql", "DB_NAME", "-u", "USER", "-pPASSWORD"], stdin=PIPE, stdout=PIPE)
                proc.communicate('source ' + fileInput)[0]
        except BaseException as ex:
            print("ERROR:", ex)
            sys.exit()

      

But I am getting this error:

ERROR: must be str, not _io.TextIOWrapper

How can i do this?

+3


source to share


2 answers


You need to pass the content of the file, not the file.

proc.communicate('source ' + fileInput.read())

      



Also, don't catch exceptions just to print and exit. This is what Python does. Leave this try / except.

+2


source


Ok I have moved the mysql commands inside bat.

from subprocess import Popen


class ImportSql:
    def execImport(self):
        p = Popen("import.bat")
        p.communicate()

      



this is normal! thank!

0


source







All Articles