python - python中奇怪的换行符错误

标签 python linux shell newline

<分区>

我一直在尝试使用 linux shell 通过 Python 将字节序列输出到文件中。问题是当我这样做时:

python -c "print '\x11\x22\x33\x44'" > new_file

new_file 包含 '\x11\x22\x33\x44\x0a'。

我在 StackOverflow 上查找了类似的问题,并尝试通过以下和许多其他类似技术去除\x0a:

python -c "print '\x11\x22\x33\x44'.rstrip('\x0a')" > new_file

然而,\x0a 拒绝离开。

有没有人遇到过这个问题?非常感谢快速修复。谢谢。

PS:我已经用各种版本的 Python 尝试过这个,包括 2.5、2.7、3.1、3.3。所有这些都会导致同样的问题。

最佳答案

这是因为 print 函数会自动在末尾添加一个换行符 (ascii 0x0a)。您可以使用 Python 3 版本的 print 来设置结束字符:

> python3 -c "print('\x11\x22\x33\x44', end='')" > new_file
> hexdump -C new_file
11 22 33 44

如果你真的需要使用Python 2,你可以使用this trick在终端中运行多行 Python 代码:

echo -e "import sys\nsys.stdout.write('\x11\x22\x33\x44')" | python > new_file

关于python - python中奇怪的换行符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24335002/

相关文章:

bash - 如何使用 bash 将命令输出分配给变量并读取

linux - 如何在没有查找的情况下在 linux shell 脚本中根据日期查找和删除文件?

pythonic相当于R GRanges中的reduce() - 如何折叠范围数据?

python - 使用 Beautifulsoup 的带有空格的类的正则表达式

Python pandas 数据框将函数结果应用于多列,其中 NaN

node.js - 如何使用curl 在我的本地主机 Node 服务器上执行GET?

python - 无法在linux中安装python3.3的请求

linux - 为什么我不能在 Linux 上更改 PCI 配置寄存器?

bash - 提取包含多个部分的部分文件名

python - 如何解析 (1045, "Access denied for user ' User' @'IP or host' (using password : YES)") when build django docker container?