gpt4 book ai didi

python - Python中使用tempfile和subprocess将mysql转为mongodb

转载 作者:可可西里 更新时间:2023-11-01 10:04:43 25 4
gpt4 key购买 nike

我打算使用 pymysqltempfilesubprocess 编写一个脚本,将我的 MySQL 数据库传输到 MongoDB,但是我到目前为止不要做对。

在下面的代码中:

for table_name in table_list:
cur.execute("select * from {0};".format(table_name))
with tempfile.TemporaryFile(mode='w+') as fp:
writer = csv.writer(fp)
writer.writerow([i[0] for i in cur.description])
for record in cur.fetchall():
writer.writerow(record)

fp.seek(0)
subprocess.Popen(['mongoimport', '-d', db_mongo, '-c', table_name, '--type', 'csv', '--file', *** I don't know what should be specified here ***, '--headerline'])

我尝试遍历任意mysql数据库的表名,从表中选择所有数据,将结果写出到一个临时文件中,然后使用mongoimport将文件中的数据倒入mongodb数据库。但是,第一,我不知道如何在 subprocess.Popen 函数中指出文件名。第二,有没有更好的方法来做我想做的事?我想有,但我想不出比这更好的那个......

为了您的信息,我最初使用实际的(不是临时的)文件名,但如果表太大,它会失败,因为它会在完成前一个表的 subprocess.Popen 之前尝试创建另一个从另一个表派生的文件 操作(我的意思是进入下一次迭代),它还迫使我在整个过程完成后删除文件,所以我更喜欢使用临时文件而不是实际文件,但不完全确定我是否正确。 ..

谢谢。

最佳答案

tempfile.TemporaryFile没有一个你可以得到的名字。特别是:

Under Unix, the directory entry for the file is removed immediately after the file is created.

在其他平台上,该文件可能有也可能没有目录条目,但您仍然无法从 API 获取它。

这正是tempfile.NamedTemporaryFile用于:

This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object.


请注意,即使 NamedTemporaryFile 也会在您关闭名称后立即取消链接,除非您通过 delete=False。因此,您有两个选择:

  • 使用 delete=False 并依靠操作系统在未来某个时间点清理文件。 (在 OS X 上,使用默认的每用户临时系统,我相信该文件夹将在下次注销或下次登录时被扫描和清理,这很长一段时间都不会。)
  • 等到子进程打开文件后再关闭它。这样做的明显方法是使用阻塞 subprocess.check_call 或类似的方法,而不是仅仅触发并忘记 Popen,但如果你想偷偷摸摸,你可以。例如,您可以在后台线程中执行等待和删除操作。或者,如果此脚本是更大脚本套件的一部分,您可以让它向上传递临时路径(通过标准输出、文件等)并让最后一个脚本清理所有文件。或者您可以找到一种方法来等待文件打开,而不是等待整个过程完成。或修补 mongoimport 以添加 --unlink-input-file 标志。或者……

关于python - Python中使用tempfile和subprocess将mysql转为mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18281962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com