I tried to to that like:
execfile('c:/xampp/mysql/bin/mysqldump -h localhost -u ' + username + ' -p' + password + ' ' + database + ' > ' + projectname + '.sql');
Then I see an error:
IOError: [Errno 2] No such file or directory: 'c:/xampp/mysql/bin/mysqldump -h localhost -u root -p pr > pr.sql'
What I do wrong?
I trie to write output to file like:
output = subprocess.check_output([r'c:\xampp\mysql\bin\mysqldump', '-h', 'localhost', '-u', username, '--password=', database], stdout=open(projectname + '.sql','w'))
It does not work
execfile doesn't take a whole command, but the name of the file to execute as the first argument. Moreover it's a way of calling other Python program, not a generic program - like mysqldump
.
I suggest you use subprocess.call
instead , eg
subprocess.call(['c:/xampp/mysql/bin/mysqldump', '-h', 'localhost', '-u', username, '-p' + password, database])
And then you need to take care of the redirection (typically done by your shell if you run it manually), so the full solution would be:
f = open(projectname+".sql", "w")
subprocess.call(['c:/xampp/mysql/bin/mysqldump', '-h', 'localhost', '-u', username, '-p' + password, database], stdout=f)
execfile
is designed to run python files only (the name is misleading).
Plus it has been removed from Python 3...
For your issue, just use subprocess.check_output
, splitting the arguments properly so quoting is handled automatically (never compose your command line by yourself). Here the -p
option must have the password without spaces (that's a command specificity), or use --password
which is clearer
output = subprocess.check_output([r'c:\xampp\mysql\bin\mysqldump', '-h', 'localhost', '-u', username, '--password', password, database])
Note: it seems that your password is blank (empty string), in that case, just use --password=
like explained here
output = subprocess.check_output([r'c:\xampp\mysql\bin\mysqldump', '-h', 'localhost', '-u', username, '--password=', database])
now the output of your command is in output
(if the command succeeds), you can write it into a file (well, in your case, it's true that you'be be better off with check_call
and stdout=file_handle
because you seem to need the .sql
file, not only the buffer) anyway:
with open("file.sql","w") as f:
f.write(output)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.