简体   繁体   English

为什么在著名的备份python脚本中,当目标文件夹名称包含空格时它不起作用?

[英]why in the famous backup python script, it doesn't work when target folder name contains spaces?

hello everyone: this is the famous code for backing up files. 大家好:这是备份文件的著名代码。 It works fine giving me the message ( successful back up ). 给我消息(正常备份)效果很好。 the target directory is created, but it is empty. 目标目录已创建,但为空。 But when I remove spaces from the target folder name it worked very fine. 但是,当我从目标文件夹名称中删除空格时,它工作得很好。 so, what is the problem and how to use target folders with spaces ? 那么,问题是什么?如何使用带空格的目标文件夹?

enter code here

import os
import time

source = [r'D:\python35']

target_dir = r"D:\Backup to harddisk 2016"

target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'

if not os.path.exists(target_dir):
    os.mkdir(target_dir)

zip_command = "zip -r {0} {1}".format(target, ' '.join(source))
print('zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
    print('Successful backup to', target)
else:
    print('Backup FAILED')

The problem is that Windows doesn't know that those spaces are part of the file name. 问题在于Windows不知道这些空格是文件名的一部分。 Use subprocess.call , which takes a list of parameters instead. 使用subprocess.call ,它改为使用参数列表。 On Windows, it escapes the spaces for you before calling CreateProcess . 在Windows上,它会在调用CreateProcess之前为您转义空格。

import subprocess as subp
zip_command = ["zip", "-r", target] + source
if subp.call(zip_command) == 0:
    print('Successful backup to', target)

It looks like it uses the command line: "zip -r {0} {1}".format(target, ' '.join(source) . 看起来它使用命令行: "zip -r {0} {1}".format(target, ' '.join(source)

Spaces are used to separate arguments on the command line. 空格用于分隔命令行上的参数。 If there's a space within the name, it believes it's the start of another argument. 如果名称中有空格,则认为这是另一个参数的开始。

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

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