如果未使用def,是否忽略它?

2024-10-02 06:31:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下脚本-

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首先解析两个字符串以生成文件名。如果我删除其中一个参数,它会抱怨添加了一个字符串和一个none值。你知道吗

编辑-如果我使用所有3个参数没有问题。如果我去掉-e或-c,比如这里我去掉了-e,我会得到以下异常-

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

我已更新参数以包含default=''


Tags: formatparserifargsbefilenamefileprint
1条回答
网友
1楼 · 发布于 2024-10-02 06:31:17

从您的问题来看,如果没有提供这些参数中的一个,则不清楚应该发生什么,但原则上,您可能希望提供一个默认值

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

如果命令行上没有提供特定的命令标志,则将使用该值。你知道吗


请注意,您没有使用可选的位置参数,而是使用可选的常规参数(这是默认行为)。

相关问题 更多 >

    热门问题