开发者

First Python Program - Multiple Errors

I am trying to write a python program that will eventually take a command line argument of a file, determine if its a tar or zip etc file and then exctract it accordingly. I am just trying to get the tar part working now and I am getting multiple errors. The file I am checking for resides in my ~/ directory. Any ideas would be great.

#!/usr/bin/python

import tarfile
import os

def open_tar(file):
    if tarfile.is_tarfile(file):
        try:
            tar = tarfile.open("file")
            tar.extractall()
            tar.close()
        except ReadError:
            print "File is somehow invalid or can not be handled by tarfile"
        except CompressionError:
            print "Compression method is not supported or data cannot be decoded"
        except StreamError:
            print "Is raised for the limitations that are typical for stream-like TarFile objects."
        except ExtractError:
            print "Is raised for non-fatal errors when using TarFile.extract开发者_C百科(), but only if TarFile.errorlevel== 2."

if __name__ == '__main__':
    file = "xampp-linux-1.7.3a.tar.gz"
    print os.getcwd()
    print file
    open_tar(file)

Here are the errors. IF I comment out the Read Error, I just get teh same error on the next exception as well.

tux@crosnet:~$ python openall.py
/home/tux
xampp-linux-1.7.3a.tar.gz
Traceback (most recent call last):
  File "openall.py", line 25, in <module>
    open_tar(file)
  File "openall.py", line 12, in open_tar
    except ReadError:
NameError: global name 'ReadError' is not defined
tux@crosnet:~$ 


You can clearly see in your error it states

NameError: global name 'ReadError' is not defined

ReadError is not a global python name. If you look at the tarfile documentation you will see ReadError is part of that modules exceptions. So in this case, you would want to do:

except tarfile.ReadError:
  # rest of your code

And you will need to do the same for the rest of those errors. Also, if all those errors will generate the same result (an error message of some sort, or a pass) you can simply do:

except (tarfile.ReadError, tarfile.StreamError) # and so on

Instead of doing them each on a seperate line. That's only if they will give the same exception


You would need to use except tarfile.ReadError or alternatively use from tarfile import is_tarfile, open, ReadError, CompressionError, etc. and put that inside the open_tar function instead of globally.


I think you might need tarfile.ReadError rather than just ReadError?


Okay. All your exceptions (ReadError, CompressionError etc.) are inside the tarfile module and so you'll have to say except tarfile.ReadError instead of just except ReadError.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜