【问题标题】:iPython: placing Python output into awk commandsiPython:将 Python 输出放入 awk 命令
【发布时间】:2020-04-10 08:29:58
【问题描述】:

当我尝试在 shell 命令中使用 Python 的变量时,我在 iPython 中得到以下行为。

大多数 shell 命令都可以正常工作(例如cathead 等)。虽然,我无法使用awk

$ ipython
Python 3.7.4 (default, Aug 13 2019, 20:35:49)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: path = '/home/mux/'

In [2]: file = 'test.txt'

In [3]: !echo {path+file}
/home/mux/test.txt

In [4]: !cat {path+file}
Testing shell commands in iPython

In [5]: !awk '{print $1}' {path+file}
awk: fatal: cannot open file `{path+file}' for reading (No such file or directory)

In [6]: full_path = {path+file}

In [7]: full_path
Out[7]: {'/home/mux/test.txt'}

In [8]: !awk '{print $1}' full_path
awk: fatal: cannot open file `full_path' for reading (No such file or directory)

In [9]: !awk '{print $1}' /home/mux/test.txt
Testing

谁能解释awk 和其他shell 命令之间的不同行为?

是否有任何解决方法可以使这项工作?

【问题讨论】:

  • 然而!awk '1' {file} 工作。
  • 你的 awk 程序在哪里?
  • @PierreFrançois 1 已经是最简单的awk 程序了。 awk 的默认操作是打印输入行,如果程序导致 True1 为真,那么它会打印每一行。 7 也可以!试试看awk '1' /etc/hosts
  • 我知道。所以,问题不在于 awk,而在于 Python 对 awk 的调用。

标签: shell awk jupyter-notebook ipython


【解决方案1】:

awk 正在使用诸如{}$ 之类的字符,它们在 iPython 代码中内联的 shell 命令中具有特殊含义。根据它们的预期用途(评估 python 变量或用于 shell 命令),您需要通过将它们加倍来转义它们。

你想要:

$ ipython3
Python 3.8.6 (default, Sep 25 2020, 09:36:53) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: path = "/tmp/"

In [2]: file = "test.txt"

In [3]: !echo {path+file}
/tmp/test.txt

In [4]: !cat {path+file}
hello

In [5]: !awk '{{print $$1}}' {path+file}
hello

当您有一个带有管道的复杂命令并且在管道后期调用 awk 时,情况会变得更糟,因为前面命令的行为会发生变化。

In [6]: !echo {path+file} | awk '{print $1}'
{path+file}

In [7]: !echo {path+file} | awk '{{print $$1}}'
/tmp/test.txt

最后一句话,当您编写full_path = {path+file} 时,您正在创建一个包含字符串连接的python 集。

【讨论】: