python 中的 sed 系统调用在 macOS 10.12.4 上生成 SOH 字符
sed systemcall in python produces SOH character on macOS 10.12.4
我正在尝试使用执行 sed 系统调用的 python 脚本替换 .h 文件中的某些字符。
这是变量中的行\ orig.h 我希望其中的“10”替换为数组中的值:
#define PACKET_DELAY_TIME_A 10
如果我 运行 在 bash 中使用 sed 命令,例如
sed -E 's/(#define PACKET_DELAY_TIME_A).*/ 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).*/ " + pckt_delay_A[1] + "/' variables\ orig.h > variables.h"
os.system(command)
这会生成 SOH 字符而不是预期的“#define PACKET_DELAY_TIME_A”
\u0001 2
在我的输出文件中。关于导致这种情况的原因以及如何获得预期输出的任何想法?
提前致谢!
使用原始字符串。对于普通字符串,</code> 被 Python 解释,这意味着将具有 ASCII 代码的字符 <code>1
放入字符串中,而不是传递给 shell。
command = r"sed -E 's/(#define PACKET_DELAY_TIME_A).*/ " + pckt_delay_A[1] + r"/' variables\ orig.h > variables.h"
或者,您可以使用其 re
模块在 Python 中编写执行此操作的代码,而不是调用 sed
.
我正在尝试使用执行 sed 系统调用的 python 脚本替换 .h 文件中的某些字符。
这是变量中的行\ orig.h 我希望其中的“10”替换为数组中的值:
#define PACKET_DELAY_TIME_A 10
如果我 运行 在 bash 中使用 sed 命令,例如
sed -E 's/(#define PACKET_DELAY_TIME_A).*/ 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).*/ " + pckt_delay_A[1] + "/' variables\ orig.h > variables.h"
os.system(command)
这会生成 SOH 字符而不是预期的“#define PACKET_DELAY_TIME_A”
\u0001 2
在我的输出文件中。关于导致这种情况的原因以及如何获得预期输出的任何想法? 提前致谢!
使用原始字符串。对于普通字符串,</code> 被 Python 解释,这意味着将具有 ASCII 代码的字符 <code>1
放入字符串中,而不是传递给 shell。
command = r"sed -E 's/(#define PACKET_DELAY_TIME_A).*/ " + pckt_delay_A[1] + r"/' variables\ orig.h > variables.h"
或者,您可以使用其 re
模块在 Python 中编写执行此操作的代码,而不是调用 sed
.