If I am using optional argument input for calling subprocess.Popen(command, **kwargs)
I am confronted with an interesting Inspection Warning in PyCharm when I .communicate()
on he return and wants to .decode('utf8')
the output.
Code:
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
Inspection Warning:
Unresolved attribute reference 'decode' for class 'str'
"Workaround":
Since the default of the output of .communicate()
is bytestring (as described here) it shouldn't be a runtime problem if the function is not called with encoding
as an optional argument. Nevertheless I am not pleased with this, given that in future this might happen and causes an AttributeError: 'str' object has no attribute 'decode'
The straightforward answer would be to make an if-case or a try-catch-operation around the decoding arguments, like this:
if 'encoding' in kwargs.keys():
return out, err
else:
return out.decode('utf8'), err.decode('utf8') if err else err
Or:
try:
return out.decode('utf8'), err.decode('utf8') if err else err
catch AttributeError:
return out, err
But I would not get rid of the Inspection warning this way.
So how to exclude an optional argument out of the **kwargs parameter to get rid of the inspection warning?
Ignoring unresolved reference problem is not an option.
I have tried to set the encoding parameter to None as default: subprocess.Popen(command, encoding=None, **kwargs)
, which did not work.