检查函数中是否传递了参数的最佳pythonic方法?是否可以进行内联检查?

2024-09-27 00:14:59 发布

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

我正在做一个简单的函数,用mutt发送邮件。有时我需要发送附件,有时不需要,所以我需要检查参数“attachment”上是否有内容。现在我的代码如下所示:

def sendMail(destino,asunto,cuerpo,adjunto):
    try:
        os.system('echo "' + cuerpo + '" | mutt -s "' + asunto + '" ' + destino)

如何正确地检查“adjunto”(附件变量)是否包含某些内容,并且仅当存在附件时才将“-a adjunto”添加到命令中?我知道我可以做一个常规的“如果”语句并使用不同的操作系统如果我有一些附件,但我想知道是否有任何方式做检查内联。像“。。。。。asunto+'“'+destino(('+'+adjunto),如果adjunto=true)”

PS:我知道代码还没有完成,但我想知道如何有效地检查附件。你知道吗


Tags: 函数代码内容附件attachment参数def邮件
3条回答

您可以使用adjunto的默认值,在定义函数时可以这样做:

def sendMail(destino, asunto, cuerpo, adjunto=None):
    try:
        os.system('echo "' + cuerpo + '" | mutt -s "' + asunto + '" ' + destino)

您还可以将语言hack与或命令一起使用:

adjunto=None
print(adjunto or 'a')

Output:
    a

它不会给你的字符串添加任何内容。你知道吗

顺便说一句,你应该使用'.format函数,它更像python函数。你知道吗

os.system('echo "{}" | mutt -s "{}" {}'.format(cuerpo, asunto, destino)

你可以这样做:

destino + ((" " + adjunto) if adjunto else "")

但是您可能不应该这样做,除非您非常确定附件的名称实际上是一个文件名,而不是某个恶意shell命令。并考虑使用subprocess模块而不是os.system。你知道吗

可以在Python中使用单行if语句:output if condition else other_output

你的例子是这样的:

'-a {}'.format(adjunto) if adjunto != None else ''

所以你的代码可以是:

    adjunto = '-a {}'.format(adjunto) if adjunto != None else ''
    os.system('echo "' + cuerpo + '" | mutt -s "' + adjunto + '" ' + destino)

相关问题 更多 >

    热门问题