views:

614

answers:

3

Hi.

Python 2.5.1

http://www.cgsecurity.org/wiki/After_Using_PhotoRec

I've just run PhotoRec and the code given as a way to sort file types into their own folder is coming back with this error. Any suggestions on how to alter? Thanks :

[EDIT2: Two points:

  1. This question was voted down because it was a 'usage' of code, somehow not a programming question. Does it qualify as a coding question? I argue yes.
  2. I've gone back and edited the page where the code came from to clarify the need for parameters for the benefit of others.]

    gyaresu$ python recovery.py Traceback (most recent call last): File "recovery.py", line 8, in source = sys.argv[1] IndexError: list index out of range

Script:

#!/usr/bin/env python
import os
import os.path
import shutil
import string
import sys

source = sys.argv[1]
destination = sys.argv[2]

while os.path.exists(source) != True:
    source = raw_input('Enter a valid source directory\n')
while os.path.exists(destination) != True:
    destination = raw_input('Enter a valid destination directory\n')

for root, dirs, files in os.walk(source, topdown=False):
    for file in files:
        extension = string.upper(os.path.splitext(file)[1][1:])
        destinationPath = os.path.join(destination,extension)

        if os.path.exists(destinationPath) != True:
            os.mkdir(destinationPath)
        if os.path.exists(os.path.join(destinationPath,file)):
            print 'WARNING: this file was not copied :' + os.path.join(root,file)
        else:
            shutil.copy2(os.path.join(root,file), destinationPath)
+2  A: 

It simply means that the program is expecting two command line arguments: source and destination. If you wish to use the same code in another function, replace sys.argv[1] and [2] with your own variables.

codelogic
A: 

Since the script is going to ask for paths if they don't exist, you could make the program arguments optional.

Change

source = sys.argv[1]
destination = sys.argv[2]

to

source = sys.argv[1] if len(sys.argv > 1) else ""
destination = sys.argv[2] if len(sys.argv > 2) else ""
MizardX
+1  A: 

Or you can modify the original script and add

if len(sys.argv) != 3:
    print "Require 2 arguments: %s <source> <destination>" %(sys.argv[0])
    sys.exit(1)

after the import statements for proper error handling.

rajasaur
+1: Not what they asked. However, the OP failed to actually read the script and see what the command line args are. This will -- to a limited extent -- help someone who can't seem to read the script.
S.Lott