using subprocess.call with mysqldump

2019-06-26 08:20发布

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.

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

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])

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

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

2条回答
Deceive 欺骗
2楼-- · 2019-06-26 08:37

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)
查看更多
Fickle 薄情
3楼-- · 2019-06-26 08:39

Could you use the --result-file=file argument for mysqldump?

might have to change check_output to subprocess.call for this to complete.

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.

查看更多
登录 后发表回答