git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

python2 vs python3


On Sat, Oct 19, 2019 at 5:29 AM Jagga Soorma <jagga13 at gmail.com> wrote:
>
> Hello,
>
> I am writing my second python script and got it to work using
> python2.x.  However, realized that I should be using python3 and it
> seems to fail with the following message:
>
> --
> Traceback (most recent call last):
>   File "test_script.py", line 29, in <module>
>     test_cmd = ("diskcmd -u " + x + " | grep -v '\*' | awk '{print $1,
> $3, $4, $9, $10}'" )
> TypeError: Can't convert 'bytes' object to str implicitly
> --
>
> I then run this command and save the output like this:
>
> --
> test_info = (subprocess.check_output( test_cmd,
> stderr=subprocess.STDOUT, shell=True )).splitlines()
> --
>
> Looks like the command output is in bytes and I can't simply wrap that
> around str().  Thanks in advance for your help with this.

That's correct. The output of the command is, by default, given to you
in bytes. But most likely, they're bytes in some well-known encoding -
probably UTF-8 - so you should be able to just tell check_output this,
and it'll give you text back. Just add another parameter:

subprocess.check_output(test_cmd, stderr=subprocess.STDOUT,
shell=True, encoding="utf8")

In general, the way to turn bytes into text is to decode them, using
some named encoding.

ChrisA