Issue
I'm trying to run this code for multiple python interpreter version. I'm getting an error for python3+. I would like to know if it is possible to run this piece of code for both python interpreter versions.
output = subprocess.check_output(['ls', '-la'], **(dict() if sys.version_info[0] < 3 else dict(text=True)))
if sys.version_info < (3, 0):
output = output.decode()
Works fine for python 2.x. But, for python3.x it output the fallowing error:
File "/usr/lib/python3.6/subprocess.py", line 356, in check_output **kwargs).stdout
File "/usr/lib/python3.6/subprocess.py", line 423, in run
with Popen(*popenargs, **kwargs) as process:
TypeError: __init__() got an unexpected keyword argument 'text'
Solution
"text" parameter is only available in version 3.7. Which means that your code will fail on an older python 3 version.
If you want to make it run on most versions, it's better to just forget about this, and use decode
if you're using python 3. I like to use bytes is not str
to check for this. But you can use a version check as well.
output = subprocess.check_output(['ls', '-la'])
if bytes is not str:
output = output.decode()
you need to decode output because check_output
returns a bytes
object, which needs decoding in python 3 if you want it to be a str
.
Decoding with python 2 would work but would return a unicode
object. The above method guarantees to produce a str
object whatever the version.
Answered By - Jean-François Fabre
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.