我正在使用此代码从外部程序获取标准输出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
communic()方法返回一个字节数组:
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
但是,我想将输出作为普通的Python字符串.所以我可以这样打印:
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
Run Code Online (Sandbox Code Playgroud)
我认为这是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.
我有一个遗留应用程序只是开始行为不端,无论出于何种原因我不确定.它会生成一堆HTML,并由ActivePDF转换为PDF报告.
这个过程是这样的:
在那个混乱的地方,HTML模板( s)中的不间断空格编码为ISO-8859-1,因此在浏览器(FireFox)中查看文档时它们会错误地显示为"Â"字符.ActivePDF会对这些非UTF8字符产生影响.
我的问题:既然我不知道问题出在哪里,也没有时间去研究它,是否有一种简单的方法可以重新编码或找到并替换坏字符?我已经尝试通过我扔在一起的这个小功能发送它,但它把它变成了gobbledegook并没有改变任何东西.
Private Shared Function ConvertToUTF8(ByVal html As String) As String
Dim isoEncoding As Encoding = Encoding.GetEncoding("iso-8859-1")
Dim source As Byte() = isoEncoding.GetBytes(html)
Return Encoding.UTF8.GetString(Encoding.Convert(isoEncoding, Encoding.UTF8, source))
End Function
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
编辑:
我现在正在接受这个,虽然它似乎不是一个好的解决方案:
Private Shared Function ReplaceNonASCIIChars(ByVal html As String) As String
Return Regex.Replace(html, "[^\u0000-\u007F]", " ")
End Function
Run Code Online (Sandbox Code Playgroud)