在mysqldump上使用subprocess.call [英] using subprocess.call with mysqldump

查看:151
本文介绍了在mysqldump上使用subprocess.call的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Windows编写脚本已有很多年了,最近几周才开始将python视为替代方案.我正在尝试编写本机python脚本,以使用mysqldump备份mysql数据库.通常,我会通过命令行将输出>输出,而不会出现问题.

I have been scripting with windows for many years and have only started to look at python as an alternative in the last few weeks. I'm trying to write a native python script to backup a mysql database with mysqldump. I normally do this with a command line piping the output > without issue.

我看到了许多有关subprocess.popen和shell = True的答案,同样,我也看到很多声明说我应该避免shell = True

I see many answers with subprocess.popen and shell=True, equally I see many statements say I should avoid shell=True

因此,我尝试获取以下代码将我的stdout重定向到文件,所有操作均未成功

So I'm trying to get the following code to redirect my stdout to a file, all without success

sys.stdout=open("mysqldump.txt",'w')
print("testing line1")
subprocess.check_output(["mysqldump", "-u", "usernmae", "-ppassword", "-h", "dbserver_name", database_name])

如果我注释掉sys.sdout行,我会看到sqldump输出到我的屏幕,因此我知道我对此部分的语法正确.我添加了打印语句,可以看到它已写入文件mysqldump.txt.但是当完全运行时,不会将任何内容转储到屏幕或文件中

If I comment out the sys.sdout line I see the sqldump outputting to my screen so I know I have the syntax correct for this part. I added the print statement and can see this gets written to the file mysqldump.txt. But when run in full there is no dump to the screen or the file

有什么想法吗?我正在尝试避免使用shell解决方案

Any ideas? I'm trying to avoid using shell solution

推荐答案

您尝试执行的操作无效,因为修改sys.stdout仅会影响print之类的Python级别的语句,而不会影响C的较低级别的写操作,尤其是那些由外部程序执行的程序.您想告诉subprocess创建一个管道,就像使用>重定向那样,

What you tried to do doesn't work because modifying sys.stdout only affects Python-level statements such as print, not lower-level writes from C, and particularly not those performed by an external program. You want to tell subprocess to create a pipe, like you did with the > redirection, which goes like this:

with open("mysqldump.txt",'w') as out:
    subprocess.check_call(["mysqldump", "-u", "usernmae", "-ppassword",
                           "-h", "dbserver_name", database_name],
                          stdout=out)

这篇关于在mysqldump上使用subprocess.call的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆