0

I'm trying to write my first Python script, and it is not going well.

I am trying to copy an entire local directory on my Ubuntu machine and place it and its contents in a different on my OS. I did some research and found distutils.dir_util.copy_tree(src,dst) should do just that.

This is the contents of my backup_images.py file:

import os
import sys

src = '/nodeGit/code/assets/images'
dst = '/usr/images_backup'

distutils.dir_util.copy_tree(src,dst)

When I run it, I get error(s) on every line. When I run ./backup_images.py in terminal, this is the output:

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

If I run the same command with sudo (sudo ./backup_images.py), I get completely different errors:

./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 ")")

Based on the first couple errors of this, (src: not found,dst: not found), it seems Python isn't able to find the directories I assigned the src and dst files to. Is this correct?

Because of the changing errors, I'm unsure of how to fix my code.

velkoon
  • 871
  • 3
  • 15
  • 35
  • 2
    Possible duplicate of [Unable to run .py file from putty, Syntax error: word unexpected (expecting ")")](http://stackoverflow.com/questions/33075561/unable-to-run-py-file-from-putty-syntax-error-word-unexpected-expecting) – Mike Scotty Apr 12 '17 at 11:40
  • 3
    Looks like you're executing the ``py`` script with the bash shell instead of the ``python`` binary. – Mike Scotty Apr 12 '17 at 11:41
  • Yes, that seemed to be the issue. Thanks. Now I'm getting an error, `name 'distutils' is not defined`, but I'd probably have to open a new Question for that if I'm unable to fix it/find an answer on my own, hm?... – velkoon Apr 12 '17 at 11:44
  • You're not importing ``distutils`` – Mike Scotty Apr 12 '17 at 11:45
  • `import distutils` wasn't sufficient to fix the error (nothing was imported into the directory on execute)...Am I missing something? I imagine I will want to use `distutils` in the future – velkoon Apr 12 '17 at 12:02

1 Answers1

2

Don't use distutils to do this. Instead use shutil.copytree() to perform a recursive copy of a directory and all its files and subdirectories.

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))
mhawke
  • 84,695
  • 9
  • 117
  • 138