2013-04-07 53 views
2

我想在python腳本中保存mysql數據庫轉儲。以下是我有:Mysqldump與python

filepath = os.path.join(BACKUPS_FOLDER, '%s.sql' % date) 
print filepath # /Users/david/Desktop/updates/_backups/2013-04-07.sql 
subprocess.call(shlex.split('mysqldump -u root updates > %s' % filepath)) 

我得到以下錯誤:

mysqldump: Couldn't find table: ">" 

我在做什麼錯誤嗎?

+0

什麼,當你用引號括起來%S會怎樣? ''%s'' – seanbreeden 2013-04-07 22:52:55

+0

我想你在調用mysqldump時沒有shell,所以它會通過'>'作爲參數(在這種情況下作爲表名) – agim 2013-04-07 22:57:19

回答

3

您可以使用選項--result-file=filesubprocess.call(shlex.split('mysqldump -u root updates --result-file=%s' % filepath)))調用mysqldump,因爲它會將>解釋爲表名。

+0

非常感謝你的提示! – David542 2013-04-07 23:00:06

+0

歡迎您! – agim 2013-04-07 23:02:03

0

這是我做的,用communicate()得到輸出,然後寫入文件:

date = str(datetime.datetime.now().date()) 
filepath = os.path.join(BACKUPS_FOLDER, '%s.sql' % date) 

args = shlex.split("mysqldump -u root updates") 
p1 = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
dump_output = p1.communicate()[0] 

f = open(filepath, "wb") 
f.write(dump_output) 
f.close()