【问题标题】:How to exclude an optional argument out of the **kwargs parameter in python?如何从 python 中的 **kwargs 参数中排除可选参数?
【发布时间】:2021-07-16 15:42:22
【问题描述】:

如果我使用可选参数输入来调用 subprocess.Popen(command, **kwargs),当我 .communicate() 返回并想要 .decode('utf8') 输出时,我会在 PyCharm 中遇到一个有趣的检查警告。

代码:

def my_call(command, **kwargs):
    process = subprocess.Popen(command, **kwargs)
    out, err = process.communicate()
    return out.decode('utf8'), err.decode('utf8') if err else err  # err could be None

检查警告:

Unresolved attribute reference 'decode' for class 'str'

“解决方法”:

由于.communicate() 的默认输出是字节串(as described here),因此如果未使用encoding 作为可选参数调用该函数,则它不应该是运行时问题。尽管如此,我对此并不满意,因为将来可能会发生这种情况并导致AttributeError: 'str' object has no attribute 'decode'

直接的答案是围绕解码参数进行 if-case 或 try-catch 操作,如下所示:

if 'encoding' in kwargs.keys():
    return out, err
else:
    return out.decode('utf8'), err.decode('utf8') if err else err

或者:

try:
    return out.decode('utf8'), err.decode('utf8') if err else err
catch AttributeError:
    return out, err

但是我不会以这种方式摆脱检查警告。

那么如何从 **kwargs 参数中排除一个可选参数以摆脱检查警告?

忽略未解决的参考问题不是一种选择。 我尝试将编码参数默认设置为无:subprocess.Popen(command, encoding=None, **kwargs),但不起作用。

【问题讨论】:

  • if 'encoding' in kwargs: del kwargs['encoding'] ?
  • if 'encoding' in kwargs: kwargs.pop('encoding') ?
  • 即使没有if - kwargs.pop('encoding', None) ?

标签: python subprocess popen keyword-argument


【解决方案1】:

Python 中的返回类型是硬编码的,不依赖于函数的输入参数(至少据我所知)。因此,将输入参数更改为subprocess.Popen(command, encoding=None, **kwargs) 不会对函数的预期返回类型产生任何影响。为了摆脱警告,我的建议是结合你的 try-catch 块使用打字:

def my_call(command, **kwargs):
    process = subprocess.Popen(command, **kwargs)
    err: bytes
    out: bytes 
    out, err = process.communicate()
    try:
        return out.decode('utf8'), err.decode('utf8') if err else err
    catch AttributeError:
        # Optionally throw/log a warning here
        return out, err

或者,您可以使用一个版本,其中使用if-condition 和isinstance(err,bytes) and isinstance(out, bytes),这也可能解决警告并且不会引发错误,但在 Python 中,您请求宽恕而不是许可 @987654321 @

【讨论】:

  • 注意:ByteString 会触发类似的警告。请改用bytes
  • 感谢您的提示。如果您还没有看到该功能:您可以在左下角编辑答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 2016-08-16
  • 2015-07-14
  • 2012-04-09
  • 2012-01-01
  • 1970-01-01
相关资源
最近更新 更多