Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

like image 384
Rob Avatar asked Jun 08 '14 06:06

Rob


2 Answers

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)
like image 128
user4815162342 Avatar answered Sep 19 '22 20:09

user4815162342


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.

like image 24
jwillis0720 Avatar answered Sep 17 '22 20:09

jwillis0720