2017-05-09 86 views
3

我必须启动一个python sql文件。 该文件是针对mysql的。 我试着这样说:从Python运行SQL文件

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() 

但我得到这个错误:

ERROR: must be str, not _io.TextIOWrapper

我该怎么办?

+0

这看起来像你想要的。 http://stackoverflow.com/a/4563950/1394353请注意源使用的是 - 文件名,而不是内容。所以不要打开文件 –

回答

2

您需要传递文件的内容,而不是文件对象。

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

此外,请不要捕捉例外只是为了打印它们并退出。这就是Python已经做的。离开那个尝试/除了。

0

好的,我移动了蝙蝠内的mysql指令。

from subprocess import Popen 


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

没关系! 谢谢!