简体   繁体   English

使用subprocess.call和mysqldump

[英]using subprocess.call with mysqldump

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. 我已经用windows编写了多年的脚本,并且在过去的几周里才开始将python作为替代品。 I'm trying to write a native python script to backup a mysql database with mysqldump. 我正在尝试编写一个本机python脚本来使用mysqldump备份mysql数据库。 I normally do this with a command line piping the output > without issue. 我通常使用命令行管道输出>没有问题。

I see many answers with subprocess.popen and shell=True, equally I see many statements say I should avoid shell=True 我看到subprocess.popen和shell = True有很多答案,同样我看到很多语句说我应该避免使用shell = True

So I'm trying to get the following code to redirect my stdout to a file, all without success 所以我试图获取以下代码将我的stdout重定向到一个文件,都没有成功

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

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. 如果我注释掉sys.sdout行,我会看到sqldump输出到我的屏幕,所以我知道我的语法正确。 I added the print statement and can see this gets written to the file mysqldump.txt. 我添加了print语句,可以看到它被写入文件mysqldump.txt。 But when run in full there is no dump to the screen or the file 但是当完全运行时,屏幕或文件没有转储

Any ideas? 有任何想法吗? I'm trying to avoid using shell solution 我试图避免使用shell解决方案

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. 您尝试执行的操作不起作用,因为修改sys.stdout只会影响Python级语句(如print ,而不会影响C的低级写入,尤其不会影响外部程序执行的操作。 You want to tell subprocess to create a pipe , like you did with the > redirection, which goes like this: 你想告诉subprocess创建一个管道 ,就像你使用>重定向一样,它是这样的:

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

Could you use the --result-file=file argument for mysqldump? 你能为mysqldump使用--result-file = file参数吗?

might have to change check_output to subprocess.call for this to complete. 可能必须将check_output更改为subprocess.call才能完成此操作。

or 要么

subprocess.call(["mysqldump", "-u", "usernmae", "-ppassword", "-h", "dbserver_name", database_name],stdout=open('myfile.txt','w'))

edit: myfile.txt will close after subprocess is done. 编辑:myfile.txt将在子进程完成后关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM