bytes.split()
method does not accept str
(Unicode type in Python 3):
>>> b'abc'.split("\n")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Type str doesn't support the buffer API
The error message is improved in Python 3.5:
>>> b"abc".split("\n")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
"\n"
(str
type) is a Unicode string (text) that is not bytes
-like (binary data) in Python 3.
To get the output of whoami
command as a Unicode string:
#!/usr/bin/env python
from subprocess import check_output
username = check_output(['whoami'], universal_newlines=True).rstrip("\n")
universal_newlines
enables text mode. check_output()
redirects child's stdout automatically and raises an exception on its nonzero exit status.
Note: shell=True
is unnecessary here (you don't need the shell, to run whoami
).
Unrelated: to find out whether you are root
in Python, you could use geteuid()
:
import os
if os.geteuid() == 0:
# I'm root (or equivalent e.g., `setuid`)
If you need to find out what is the current user name in Python:
import getpass
print('User name', getpass.getuser())
Beware: don't use getuser()
for access control purposes!