Python 子进程不支持复杂的 Linux 命令

标签 python linux awk sed

我在 Linux 中有一个命令,它给出以下输出:

1425463080: 0.0000000000e+00 0.0000000000e+00
1425463085: 0.0000000000e+00 0.0000000000e+00
1425463090: 0.0000000000e+00 0.0000000000e+00
1425463095: 0.0000000000e+00 0.0000000000e+00
...

为了使其更具可读性,我使用 awk 命令,如下所示:

my command | awk 'NR > 2 {printf "%s %0.2f %0.2f\n", $1, $2, $3;}'

现在删除多余的:,我使用 sed 如下:

my command | awk 'NR > 2 {printf "%s %0.2f %0.2f\n", $1, $2, $3;}' | sed 's/://g'

这样我就可以得到以下预期的输出:

1425463715 0.16 0.42
1425463720 0.16 0.42
1425463725 0.16 0.42
...

现在我想通过Python运行上面的命令。但是我在通过Python子进程模块运行它时遇到了很多问题。例如我面临以下错误:

('', 'awk: NR > 2 {printf "%s %0.2f %0.2f\nawk: ^ unterminated string\n')

即使我将命令指定为:

cmd = """ my command | awk 'NR > 2 {printf "%s %0.2f %0.2f\n", $1, $2, $3;} """
subprocess.Popen(cmd, ...)

...仍然不起作用。

请告诉我我的 Linux 命令是否正确。如果是,那么我如何通过Python子进程执行它。

最佳答案

您需要转义\n转义序列; Python 也解释了这一点;您还缺少 awk 命令中的结束 ' 单引号:

cmd = """ 'my command' | awk 'NR > 2 {printf "%s %0.2f %0.2f\\n", $1, $2, $3;}' """

或使用原始字符串:

cmd = r""" 'my command' | awk 'NR > 2 {printf "%s %0.2f %0.2f\n", $1, $2, $3;}' """

请注意,Python 也完全有能力完成这项工作,无需在中间使用额外的 shell 二进制文件来解释 shell 语法。

关于Python 子进程不支持复杂的 Linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853964/

相关文章:

linux - 如何在shell脚本中添加缩进

linux - 英镑配置,通配符的 https 重定向问题

python - 以不同的方式捕获键盘输出

regex - 如何根据行的特殊部分对文件的行进行排序

awk - 使用awk替换 `'`char

python - 使用python和OpenCV计数图像上的单元格

python - 使用 numpy 比较并查找两个不同大小的数组之间的错误

python - 从c中的嵌入式python代码加载DLL

python从字符串中删除电话号码

python - 我可以在 Python 中按数值对文本进行排序吗?