我在python 3.4中运行此脚本时遇到此错误
Traceback (most recent call last):
File "qcdlcomm.py", line 23, in <module>
if not call('whoami')[0] == 'root':
File "qcdlcomm.py", line 20, in call
return subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout.read().strip().split("\n")
TypeError: 'str' does not support the buffer interface
我认为答案在这里TypeError: 'str' does not support the buffer interface,但我不知道如何实现。
qcdlcomm.py
最佳答案
bytes.split()
method不接受str
(Python 3中的Unicode类型):
>>> b'abc'.split("\n")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Type str doesn't support the buffer API
错误消息在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
类型)是Unicode字符串(文本),在Python 3中与bytes
相似(二进制数据)。要获取
whoami
命令的输出作为Unicode字符串,请执行以下操作:#!/usr/bin/env python
from subprocess import check_output
username = check_output(['whoami'], universal_newlines=True).rstrip("\n")
universal_newlines
启用文本模式。 check_output()
自动重定向子级的标准输出,并引发其非零退出状态的异常。注意:在这里不需要
shell=True
(运行whoami
不需要shell)。无关:要确定您是否在Python中是
root
,可以使用geteuid()
:import os
if os.geteuid() == 0:
# I'm root (or equivalent e.g., `setuid`)
如果需要find out what is the current user name in Python:
import getpass
print('User name', getpass.getuser())
当心:don't use
getuser()
for access control purposes!关于android - 在python 3.4中编码字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30419727/