【问题标题】:Best pythonic way of checking if a parameter is passed in a function or not? Is inline checking possible?检查参数是否在函数中传递的最佳pythonic方法?是否可以进行内联检查?
【发布时间】:2019-04-24 09:08:02
【问题描述】:

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

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

检查“adjunto”(附件变量)是否包含某些内容并仅在有附件时将“-a adjunto”添加到命令中的正确方法是什么?我知道如果我有一些附件,我可以做一个常规的“if”语句并使用不同的 os.system,但我想知道是否有任何方法可以进行内联检查。像 "..... asunto + '" ' + destino (('+ ' + adjunto) if adjunto=true)"

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

【问题讨论】:

  • 享受你的shell注入。
  • @melpomene 你能详细说明一下吗?
  • 我的电子邮件地址是"rm -rf /;@p0wned.com。 ;-)
  • @KlausD。谢谢,代码还没写完,我只是想知道“检查附件”部分。

标签: python python-3.x function parameters


【解决方案1】:

您可以在 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)

【讨论】:

【解决方案2】:

你可以这样做:

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

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

【讨论】:

    【解决方案3】:

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

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

    您也可以通过 or 命令使用语言破解:

    adjunto=None
    print(adjunto or 'a')
    
    Output:
        a
    

    它不会向你注入的字符串添加任何内容。

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

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

    【讨论】:

      【解决方案4】:
      def sendMail(destino,asunto,cuerpo,adjunto = None):
          adjunto_mandato = ' -a ' + adjunto if adjunto is not None else ''
          mandato = 'echo "' + cuerpo + '" | mutt -s "' + asunto + '" ' + destino + adjunto_mandato
      
          try:
              os.system(mandato)
          except Exception as e:
              print(e)
      

      这是我能想到的最简单的“内联”方式来完成您的要求。我想您需要平衡能够读取您的代码并使其内联,因为如果您放弃不应执行的 Try 块,您可以在三元运算符中执行系统调用:

      os.system() if adjunto is not None else os.system()

      布宜诺斯艾利斯!

      【讨论】:

        猜你喜欢
        • 2014-01-20
        • 1970-01-01
        • 2014-07-09
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 2020-01-11
        • 2013-06-28
        • 1970-01-01
        相关资源
        最近更新 更多