【问题标题】:Python 3 Backup Failed?Python 3 备份失败?
【发布时间】:2017-07-31 18:27:22
【问题描述】:

我刚刚关注了totorial《A Byte of Python》,备份所有重要文件时出现问题。

这是我的代码:

import os

import time

source = ['"C:\\My Documents"', 'C:\\Code']

target_dir = 'D:\\Backup'

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

虽然我是windows系统,但我想我已经在系统PATH环境变量中添加了C:\Windows\GnuWin32\binIs it right? 当我在终端 it shows like this 中输入 zip

但是当我运行程序时,结果是:

Zip command is:
zip -r D:\Backup\20170310193946.Zip "C:\My Documents" C:\Code
Running:
Backup Failed

我试了又试,还是不知道为什么。

任何帮助将不胜感激。谢谢

【问题讨论】:

  • 好的,由于缺少 Windows,无法真正测试,但您的命令中传递给 os.system() 的路径可能被解释为 C 反斜杠转义字符。 Python 的os.system 实际上是C 的system(3) 的封装。我怀疑可能有一些escape-character craziness 正在进行。
  • 感谢您的回复。那么我该怎么做才能解决这个问题呢?
  • Don't use os.system at all。无论如何,这是邪恶和混乱的。确保传递给子进程的路径完全符合它们的含义。必要时使用os.path。作为路径分隔符的反斜杠字符是迟钝和邪恶的,你应该小心,因为 escapogeddon 是迟钝的。
  • 对不起,我还是看不懂。谢谢。
  • 您使用的是 linux zip 命令,在 windows 上应该会有所不同。

标签: python python-3.x operating-system


【解决方案1】:
  1. 确保您从 GnuWin32 网站安装了 zip 3.0
  2. 也许您需要将系统路径环境变量C:\Windows\GnuWin32\bin更改为C:\Program Files (x86)\GnuWin32\bin
  3. 更改路径后重新启动 IDE(在我的情况下是 PyCharm)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2021-01-22
    • 2018-10-16
    相关资源
    最近更新 更多