python - 使用 Python 启动临时 MySQL 服务器

标签 python mysql python-2.7 mysql-python

我想通过Python执行特定版本的mysqld进行单元测试。这个想法是在一个线程上执行服务器,测试并在完成后终止服务器。 (类似于 testing.mysqld ,遗憾的是它在 Windows 上不起作用。)。这是当前代码:

    #Create a temporary folder.
    base_path = tempfile.mkdtemp()

    #Extract the default files
    zipfile.ZipFile(r"O:\Tools\mysql\min_mysql.zip").extractall(base_path)

    #Setup my_ini file
    my_ini_path = os.path.join(base_path, "my.ini").replace("\\", "/")
    unix_base_path = posixpath.normpath(base_path).replace("\\", "/")

    with open(my_ini_path, 'r') as my_ini:
      filedata = my_ini.read()
    filedata = filedata.replace("{{basedir}}", unix_base_path)
    with open(my_ini_path, 'w', 0) as my_ini:
      my_ini.write(filedata)

    #Open mysqld
    args = r"O:/Tools/mysql/bin/mysqld.exe --defaults-file=\"%s\"" % (my_ini_path)
    args = shlex.split(args)
    mysqld_process = subprocess.Popen(args, shell=True)
    mysqld_process.wait()

但是如果我通过 Python 执行它,则会收到此错误:

    Could not open required defaults file:
    "c:\users\pelfeli1\appdata\local\temp\tmp2vct38\my.ini"
    Fatal error in defaults handling. Program aborted

到目前为止,我已经在开始该过程之前验证了该文件是否存在。如果我逐字打印命令并执行它,服务器运行正常。

Popen 和仅仅在 shell 中执行之间似乎有区别。我错过了什么?

最佳答案

如果您想接受它作为答案,我将在此处复制我的评论:

I don't think this is the problem, but the args string shouldn't be defined as raw (with the r). Instead, do this: 'O:/Tools/mysql/bin/mysqld.exe --defaults-file="%s"' (ie. use single quotes). Unless you intend to pass the backslashes to the command line

现在,考虑以下两个字符串

 "foo\"bar\""
r"foo\"bar\""

相同。第一个呈现 foo"bar",而第二个呈现 foo\"bar\"

因此,shell 将此视为文件名:"c:\users\pelfeli1\appdata\local\temp\tmp2vct38\my.ini", 包括引号,因为有反引号 (\)。你可以这样写:

args = 'O:/Tools/mysql/bin/mysqld.exe --defaults-file="%s"' % (my_ini_path)

以防 my_ini_path 中存在空格,没有问题。

关于python - 使用 Python 启动临时 MySQL 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964674/

相关文章:

python - 在没有 shell 转义序列的情况下在 Python 中打印标准输出

python - 使用 scipy.io savemat 将多个 Python 字典转换为 MATLAB 结构数组

MySQL - 从每个 'group' 中仅选择 2 行

python - tf.nn.sigmoid_cross_entropy_with_logits 公司关于文档中的参数

Python SQL 值错误

python - 属性错误 : module 'alembic.context' has no attribute 'config'

mysql - 获取每个部门员工前2名工资的差异

php - 更新mysql列字段中的数据而不删除以前的值

python - func (1) 返回的数组与 Python 中的大小不匹配

python-2.7 - GNU Parallel 在大文件上运行 Python 脚本