-1

I have the following script -

import os, errno
import argparse

def removecompressed(filename):
    try:
        os.remove(filename)
        print('Removing {}'.format(args.compressedfile))
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        print ('File {} does not exist in location {}!'.format(args.compressedfile, args.localpath))
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occured

def removeencrypted(filename):
    try:
        os.remove(filename)
        print('Removing {}'.format(args.encryptedfile))
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        print ('File {} does not exist in location {}!'.format(args.encryptedfile, args.localpath))
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occured

parser = argparse.ArgumentParser()
parser.add_argument('-p', '--localpath', type=str, default='', help="the path containing the files")
parser.add_argument('-c', '--compressedfile', type=str, default='', help="the compressed file to be deleted")
parser.add_argument('-e', '--encryptedfile', type=str, default='', help="the encrypted file to be deleted")
args = parser.parse_args()

removecompressed(args.localpath + args.compressedfile)
removeencrypted(args.localpath + args.encryptedfile)

But I want the -e and -c arguments to be optional. How would I go about doing this?

I understand this reply: Argparse optional positional arguments?

but the problem is that the def is parsing 2 strings together first to make the filename. If I remove one of the arguments it complains about adding a string and a none value.

edit - if I use all 3 arguments there's no problem. If I remove the -e or -c for example here I've removed the -e I get the following exception -

Traceback (most recent call last):
  File "cleanup.py", line 35, in <module>
    removeencrypted(args.localpath + args.encryptedfile)
TypeError: Can't convert 'NoneType' object to str implicitly

I've updated my arguments to include default=''

Community
  • 1
  • 1
whoisearth
  • 4,080
  • 13
  • 62
  • 130

1 Answers1

2

It's unclear from your question what should happen if one of those arguments isn't provided, but in principle, you probably want to provide a default value:

parser.add_argument('-c', '--compressedfile', type=str, default='', help="the compressed file to be deleted")

This is the value which will be used if the particular command flag isn't provided on the command line.


Note that you're not using optional positional arguments, you're using optional regular arguments (which is the default behavior).

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • I've updated to include the error I get when removing one of the arguments (-e). I also included the default='' value. – whoisearth May 12 '14 at 16:53