Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running SQL file from Python

I have to launch a python sql file. The file is for mysql. I tried it like this:

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 get this error:

ERROR: must be str, not _io.TextIOWrapper

how can I do?

like image 824
matteo Avatar asked Feb 09 '26 15:02

matteo


1 Answers

You need to pass the contents of the file, not the file object.

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

Also, please don't catch exceptions just to print them and exit. That's what Python does already. Leave out that try/except.

like image 86
Daniel Roseman Avatar answered Feb 12 '26 15:02

Daniel Roseman