나는 다음 스크립트가 -사용하지 않을 경우 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
내가 기본을 포함하는 내 인수를 업데이트 한을 = ''
'if' 문을 사용하여'None' 인 경우 인수를 테스트 할 수 있습니까? – Evert