Shell iPython:将Python输出放入awk命令
当我尝试在shell命令中使用Python的变量时,我在iPython中得到了以下行为 大多数shell命令(例如,Shell iPython:将Python输出放入awk命令,shell,awk,jupyter-notebook,ipython,Shell,Awk,Jupyter Notebook,Ipython,当我尝试在shell命令中使用Python的变量时,我在iPython中得到了以下行为 大多数shell命令(例如,cat,head等)都可以正常工作。尽管如此,我无法使用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
cat
,head
等)都可以正常工作。尽管如此,我无法使用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
使用的字符如{
、}
和$
在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\u path={path+file}
时,您正在创建一个包含字符串串联的python集。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集。然而!awk'1'{file}
有效。你的awk程序在哪里?@PierreFrançois1
已经是最简单的awk
程序了awk
的默认操作是,如果程序结果为True
且1
为True,则打印输入行,因此它会打印每一行<代码>7也有效!试试看,我知道。因此,问题不在于awk,而在于Python对awk的调用!awk'1'{file}有效。你的awk程序在哪里?@PierreFrançois1
已经是最简单的awk
程序了awk
的默认操作是,如果程序结果为True
且1
为True,则打印输入行,因此它会打印每一行<代码>7也有效!试试看,我知道。因此,问题不在于awk,而在于Python对awk的调用。