在python 3.4中编码一个字符串

时间:2015-05-24 03:14:50

标签: android python-3.x buffer root

我在python 3.4中运行此脚本时出现此错误

taskkill

我认为答案在TypeError: 'str' does not support the buffer interface,但我不知道如何实现它。

qcdlcomm.py

3 个答案:

答案 0 :(得分:2)

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 type)是一个Unicode字符串(文本),它不是bytes - 就像Python 3中的(二进制数据)一样。

要将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(您不需要shell来运行whoami)。

无关:要了解您是否在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!

答案 1 :(得分:0)

在python3中对字符串的处理方式不同。字符串与字节不同。调用whoami得到的是一个字节数组。要修复call函数,只需将字节解码为字符串:

def call(cmd,hide_stderr=True):                                                 
    return subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE).stdout.read().decode("utf-8").strip().split("\n")

这是Convert bytes to a Python string中提到的类似问题。

请注意,这只是一个快速修复,但适用于您的用例。只需将.decode('utf-8')插入.read().strip()之间的第20行。

答案 2 :(得分:0)

通常,如果你想在Python 3中使用Popen的文本模式(假设你使用cPython实现),你可以将encodingerroruniversal_newlines参数传递给Popen构造函数。例如:

return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, universal_newlines=True).stdout.read().strip().split("\n")

那是因为在__init__Popen的cPython实现中有以下一行:

text_mode = encoding or errors or universal_newlines

这也是cPython内部的check_output - 它确保input关键字参数(如果存在且None)具有适当的类型并将关键字参数传递给{{1 (稍后调用run):

Popen

subprocess.py source中查看更多内容。