【发布时间】:2020-04-10 08:29:58
【问题描述】:
当我尝试在 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 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的默认操作是打印输入行,如果程序导致True和1为真,那么它会打印每一行。7也可以!试试看awk '1' /etc/hosts -
我知道。所以,问题不在于 awk,而在于 Python 对 awk 的调用。
标签: shell awk jupyter-notebook ipython