【问题标题】:sed systemcall in python produces SOH character on macOS 10.12.4python 中的 sed 系统调用在 macOS 10.12.4 上生成 SOH 字符
【发布时间】:2017-08-24 23:20:36
【问题描述】:

我正在尝试使用执行 sed-systemcall 的 python 脚本替换 .h 文件中的某些字符。

这是 variables\ orig.h 中我希望将“10”替换为数组中的值的行:

#define PACKET_DELAY_TIME_A 10

如果我在 bash 中运行 sed 命令,例如

sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 2/' variables\ orig.h > variables.h

这完全正常,输出如预期,即“10”被替换为“2”

但是,当我使用 python 系统调用来执行此操作时,例如

import os

pckt_delay_A = ["1","2","5","10","20"]
command = "sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 " + pckt_delay_A[1] + "/' variables\ orig.h > variables.h"
os.system(command)

这会产生 SOH 字符而不是预期的 '#define PACKET_DELAY_TIME_A'

\u0001 2

在我的输出文件中。关于导致此问题的原因以及如何获得预期输出的任何想法? 提前致谢!

【问题讨论】:

  • 如果将 ' " + pckt_delay_A[1] + " ' 替换为 ' " + "2" + " ' 会发生什么?

标签: python bash sed system-calls


【解决方案1】:

使用原始字符串。对于普通字符串,\1 被 Python 解释,这意味着将一个带有 ASCII 码 1 的字符放入字符串中,而不是传递给 shell。

command = r"sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 " + pckt_delay_A[1] + r"/' variables\ orig.h > variables.h"

或者,您可以使用 Python 的 re 模块编写执行此操作的代码,而不是调用 sed

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2017-04-19
    相关资源
    最近更新 更多