python - 为什么当使用 os.system() 或 subprocess.Popen() 从 Python 调用时我的 MySQL 存储过程不执行?

标签 python mysql stored-procedures command-line subprocess

我有一个创建并执行存储过程的 .sql 文件。 .sql文件的结构是这样的:

delimiter $$
drop procedure if exists `myProcedure`$$
create procedure `myProcedure` (
  input INT
)
BEGIN
  ... sql statements;
END $$

call myProcedure(10);
$$

当通过以下方式从 shell 执行此操作时,将创建存储过程并正确执行末尾的 call 语句。

mysql -uuser -ppassword -hhost db_name < mysql_proc.sql

但是,当我从 python 脚本执行上述命令时,最后的 call 语句没有被执行。这就是我在 Python 脚本中执行上述命令的方式:

command = 'mysql -uuser -ppassword -hhost db_name < mysql_proc.sql'
mysql_cmd_proc = subprocess.Popen(command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
stdout_val, stderr_val = mysql_cmd_proc.communicate()
print 'mysql command stdout: %s' % stdout_val
print 'mysql command stderr: %s' % stderr_val

没有错误或返回输出(stdout_valstderr_val 只是空字符串)。我尝试围绕 call myProcedure(10); $$ 也带有 BEGINEND $$ block ,但这也没有帮助。有什么原因导致这可能成为问题吗?

最佳答案

command = 'mysql -uuser -ppassword -hhost db_name < mysql_proc.sql'
mysql_cmd_proc = subprocess.Popen(command,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)

不要使用shell=True(它应该是False,默认情况下)。另外,将命令作为列表传递。

这样做:

>>> import shlex
>>> command = 'mysql -uuser -ppassword -hhost db_name < mysql_proc.sql'
>>> mysql_cmd_proc = subprocess.Popen(shlex.split(command),   # shlex.split
...                                   stdout=subprocess.PIPE,
...                                   stderr=subprocess.PIPE)

shlex.split

关于python - 为什么当使用 os.system() 或 subprocess.Popen() 从 Python 调用时我的 MySQL 存储过程不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4859805/

相关文章:

sql - 填写表中缺失的天数

python - 为什么Python中的 "[ ] and {}"表达式返回[]?(为什么[]和{}为假?)

python - 为什么 Numpy.array 比获取子列表的内置列表慢

mysql - 如何创建一个列来存储 MySQL 中另一个表中所有相关记录的总和

mysql - Rails 3.2.3 希望在 mysql 生产环境中使用 sqlite3 gem

sql - 用于将数据从一个表插入到具有相同列名的另一个表的存储过程

sql-server - SQL Server查询执行计划在已使用的索引上显示错误 "actual row count"并且性能非常慢

python - 从 Python 中的 Generator 类生成 n 行

python - 使用 Polars 生成运行记录,其中一个月的期末余额将成为下个月的期初余额

mysql - 查询选择公司数据