我在python 3.4中运行此脚本时出现此错误
taskkill
我认为答案在TypeError: 'str' does not support the buffer interface,但我不知道如何实现它。
答案 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())
答案 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实现),你可以将encoding
,error
或universal_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中查看更多内容。