我正在尝试编写我的第一个Python脚本,并且进展不顺利。
我正在尝试在我的Ubuntu计算机上复制整个本地目录,并将其及其内容放在我的操作系统上。我做了一些研究,发现distutils.dir_util.copy_tree(src,dst)
应该这样做。
这是 backup_images.py 文件的内容:
import os
import sys
src = '/nodeGit/code/assets/images'
dst = '/usr/images_backup'
distutils.dir_util.copy_tree(src,dst)
当我运行它时,我会在每一行上收到错误。当我在终端中运行./backup_images.py
时,这是输出:
./backup_images.py: line 1: src: command not found
./backup_images.py: line 2: dst: command not found
./backup_images.py: line 4: syntax error near unexpected token `src,dst'
./backup_images.py: line 4: `distutils.dir_util.copy_tree(src,dst)'
如果我使用sudo(sudo ./backup_images.py
)运行相同的命令,我会得到完全不同的错误:
./backup_images.py: 1: ./backup_images.py: src: not found
./backup_images.py: 2: ./backup_images.py: dst: not found
./backup_images.py: 4: ./backup_images.py: Syntax error: word unexpected (expecting ")")
根据前几个错误(src: not found
,dst: not found
),似乎Python无法找到我分配给src
和{{{{}}的目录1}}文件到。这是对的吗?
由于错误的变化,我不确定如何修复我的代码。
答案 0 :(得分:2)
请勿使用distutils
执行此操作。而是使用shutil.copytree()
来执行目录及其所有文件和子目录的递归副本。
import shutil
src = '/nodeGit/code/assets/images'
dst = '/usr/images_backup'
try:
shutil.copytree(src,dst)
except shutil.Error as exc:
# handle any exception that might occur
print("Got exception {} while copying {} to {}".format(exc, src, dst))