用未知编码写数据

发布于 2025-01-28 10:15:56 字数 1025 浏览 3 评论 0原文

是否可以将数据写入未知编码中的文件? 我无法解码电子邮件标题,例如消息-ID,因为如果我使用处理程序忽略或替换 https://docs.python.org/3/library/codecs。 html#错误处理器 非RFC标头将符合RFC,并且AntisPAM不会提高垃圾邮件分数。

我从Mirter协议中从Postfix那里获得字符串。我无法为Antispam保存这些数据,而是提高UnicodeError。示例:

CAT SaveFile

#!/usr/bin/python3

import sys
fh = open('test', 'w+')
fh.write(sys.argv[1])
echo žlutý | xargs ./savefile && cat test
žlutý
echo žlutý | iconv -f UTF-8 -t ISO8859-2 - | xargs ./savefile 
Traceback (most recent call last):
  File "/root/./savefile", line 5, in <module>
    fh.write(sys.argv[1])
UnicodeEncodeError: 'utf-8' codec can't encode character '\udcbe' in position 0: surrogates not allowed

输入可能是许多未知编码。 Python2中的Milter应用程序效果很好。

Is it possible write data to a file in an unknown encoding?
I cannot decode email headers, for example message-id, because if I use handler ignore or a replace
https://docs.python.org/3/library/codecs.html#error-handlers
non-RFC header will be RFC-compliant and antispam don't increase spam score.

I get string from postfix in milter protocol. I cannot save this data unchanged for antispam, raise UnicodeError. Examples:

cat savefile

#!/usr/bin/python3

import sys
fh = open('test', 'w+')
fh.write(sys.argv[1])
echo žlutý | xargs ./savefile && cat test
žlutý
echo žlutý | iconv -f UTF-8 -t ISO8859-2 - | xargs ./savefile 
Traceback (most recent call last):
  File "/root/./savefile", line 5, in <module>
    fh.write(sys.argv[1])
UnicodeEncodeError: 'utf-8' codec can't encode character '\udcbe' in position 0: surrogates not allowed

Input may be a lot of unknown encoding. Milter application in python2 works well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若有似无的小暗淡 2025-02-04 10:15:56

您要处理RAW 字节,而不是字符串。 打开以二进制模式输出文件。请注意:

sys.argv

..

注意:在UNIX上,命令行参数由OS的字节传递。 Python用文件系统编码和“ sermogateescape”错误处理程序解码。当您需要原始字节时,可以通过[OS.FSENCODE(arg)在sys.argv中获得它,

https:///docs.python.org/ 3/library/sys.html#sys.argv

so:

import sys
import os

with open('test', 'wb+') as fh:
    fh.write(os.fsencode(sys.argv[1]))

You want to handle raw bytes then, not strings. open the output file in binary mode. Note this:

sys.argv

..

Note: On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes, you can get it by [os.fsencode(arg) for arg in sys.argv].

https://docs.python.org/3/library/sys.html#sys.argv

So:

import sys
import os

with open('test', 'wb+') as fh:
    fh.write(os.fsencode(sys.argv[1]))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文