2014-05-12 2 views
-1

나는 다음 스크립트가 -사용하지 않을 경우 def를 무시합니까?

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) 

을하지만 난 -e 및 -c 인수는 선택 사양하고 싶다. 이 일을 어떻게 하죠?

나는이 대답을 이해 : Argparse optional positional arguments?

을하지만 문제는 DEF 파일 이름을 먼저 함께 2 문자열을 구문 분석이다. 인수 중 하나를 제거하면 문자열과 없음 값을 추가하는 것에 대해 불평합니다.

편집 - 3 가지 인자를 모두 사용하면 문제가 없습니다. 나는 내가 다음과 같은 예외가 얻을 -e 제거했습니다 여기에 예를 들어, -e 또는 -c 제거하는 경우 -

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 

내가 기본을 포함하는 내 인수를 업데이트 한을 = ''

+0

'if' 문을 사용하여'None' 인 경우 인수를 테스트 할 수 있습니까? – Evert

답변

2

이 불분명 그 인수 중 하나가 제공되지 않으면 귀하의 질문에서 무엇을 발생해야하지만, 원칙적으로, 당신은 아마 기본 값을 제공하려는 :이되는 것입니다 값이

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

특정 명령 플래그가 명령 행에 제공되지 않은 경우에 사용됩니다. 당신은, 당신은 (디폴트 동작)를 선택 일반 인수를 사용하고 옵션 위치 인수를 사용하지 않는


참고.

+0

인수 (-e) 중 하나를 제거 할 때 발생하는 오류를 포함하도록 업데이트했습니다. 또한 기본 = ''값도 포함 시켰습니다. – whoisearth

관련 문제