0

I try to query my hostname like

import subprocess
p2 = subprocess.check_output('hostname')
print(p2)

and the result is alway a letter b at the beginning.

b'Nick-iMac.local\n'

What could be the reason?

On my local Mac session I see:

$ hostname
Nick-iMac.local
Nick
  • 17
  • 1
  • 3

1 Answers1

1

The b sigil indicates the type of the data; it's not part of the value. It shows that this is a bytes value, not a str value.

You want to use universal_newlines=True if your Python version is new enough (but then you'll probably also want to switch to subprocess.run()).

On older Python versions, p2.decode('utf-8') will return the value converted to a string; but then you need to know the correct encoding.

Going forward, this keyword parameter is called simply text since Python 3.7, though the alias universal_newlines will continue to work. It was always a bit of a misnomer, though; text is a better summary of all the small things it does.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • See https://stackoverflow.com/a/51950538/874188 for a somewhat more involved elaboration of some of these points. – tripleee Sep 21 '18 at 15:39
  • It's not an error for a system to use a different encoding, but it's a bad smell - sort of like visiting a country where people are still allowed to smoke indoors willy-nilly. Open the windows and strive for https://utf8everywhere.org/ – tripleee Sep 21 '18 at 15:45
  • By that logic, any use of Windows is a bad smell (not that some people wouldn't agree with that statement). – ShadowRanger Sep 21 '18 at 15:59
  • @ShadowRanger Indeed! Very astute observation. – tripleee Sep 21 '18 at 16:01
  • @tripleee - thanks! I wonder how to store the result in a variable, like `p = subprocess.check_output('hostname', universal_newlines=True)` , but whenever I compare this one step later, it doesn't work as expected. `if p == 'Nick-iMac.local':` – Nick Sep 21 '18 at 19:05
  • You still have the trailing newline. – tripleee Sep 21 '18 at 19:18