简体   繁体   English

python3.6 - TypeError: write() 参数必须是 str,而不是字节 - 但不涉及文件

[英]python3.6 - TypeError: write() argument must be str, not bytes - but no files involved

the following code returns an error and I don't understand why... Running on Python 3.6以下代码返回错误,我不明白为什么...在 Python 3.6 上运行

import subprocess
import sys
import os

def execute_shell_cmd(cmd):
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        for c in iter(lambda: process.stdout.read(1), b''):
                sys.stdout.write(c)
        for e in iter(lambda: process.stderr.read(1), b''):
                sys.stderr.write(e)

execute_shell_cmd("ls -l")

The error returned: TypeError: write() argument must be str, not bytes返回的错误:TypeError: write() argument must be str, not bytes

Everything I see online talks about files and opening them with 'wb' options, but this is irrelevant here.我在网上看到的所有内容都在谈论文件并使用“wb”选项打开它们,但这在这里无关紧要。

I'm sure it's silly... Any ideas?我敢肯定这很愚蠢......有什么想法吗?

You're opening the subprocess without an encoding parameter set, so the streams are binary streams (which is an excellently sane default, considering eg something like GhostScript could output a binary PDF on stdout ).您在没有设置编码参数的情况下打开子进程,因此流是二进制流(这是一个非常理智的默认值,考虑到诸如 GhostScript 之类的东西可以 output 一个二进制 PDF on stdout )。

Do

process = subprocess.Popen(
   cmd,
   stdout=subprocess.PIPE, 
   stderr=subprocess.PIPE,
   shell=True,
   encoding='utf-8',
   errors='strict',   # could be ignore or replace too, `strict` is the default
)

if you'd like the streams to be wrapped in an UTF-8 decoder so you get strings out of them, not bytes.如果您希望将流包装在 UTF-8 解码器中,以便从中获取字符串,而不是字节。 Of course, this implies you know the output data is always UTF-8.当然,这意味着您知道 output 数据始终是 UTF-8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 类型错误:write() 参数必须是 str,而不是字节 - Python - TypeError: write() argument must be str, not bytes TypeError:write()参数必须是str,而不是字节(Python 3 vs Python 2) - TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 ) ElementTree TypeError“write()参数必须是str,而不是Python3中的字节” - ElementTree TypeError “write() argument must be str, not bytes” in Python3 编码:TypeError:write()参数必须是str,而不是bytes - Encoding: TypeError: write() argument must be str, not bytes 适用于Python3.6的Zipfile模块:写字节而不是Odoo文件 - Zipfile module for Python3.6: write to Bytes instead of Files for Odoo write()参数必须为str,而不是字节数python - write() argument must be str, not bytes python TypeError: write() 参数必须是 str,而不是 dict (Python) - TypeError: write() argument must be str, not dict (Python) TypeError:write()参数必须是str,而不是字节,UTF-16 - TypeError: write() argument must be str, not bytes, UTF-16 TypeError:write()参数必须是str,而不是保存.npy文件时的字节 - TypeError: write() argument must be str, not bytes while saving .npy file inkex.py TypeError: write() 参数必须是 str,而不是字节 - inkex.py TypeError: write() argument must be str, not bytes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM