【发布时间】: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