我想通过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/