我习惯于写很多AWK命令,但是,一直想用Python来做与awk 相同的东西而不用编写.py文件。我在Python中有基础知识,但在命令行中没有。
例如,我有以下AWK命令。 python的等价物是什么?
awk '/Classic.java/ {print $0}' somefile.log;
答案 0 :(得分:5)
Python不太适合shell单行。你可以玩The Pyed Piper:
$ ls | pyp "p[0] | pp.sort() | p + ' first letter, sorted!'"
# it gives sorted list of first letters of every line
它使用标准的Python字符串和列表方法以及自定义函数。还有pyline:
$ ls | pyline -m os 'line and os.path.abspath(line.strip())'
$ ls | pyline -r '\(.*\)' 'rgx and (rgx.group(0), rgx.group(1)) or line'
$ ls | pyline -p 'p and p.abspath() or ("# ".format(line))'
另一种方法是使用ipython
as a shell或基于浏览器的notebook(推荐)。或者,如果您想要更多的BASHWARD语法和子进程命令的选项卡完成;试试xonsh
as your shell:
xonsh$ [i*i for i in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
xonsh$ date -u
Tue Oct 6 04:25:27 UTC 2015
subprocess
and its alternatives (plumbum
, pexpect
, sarge
, sh
(module), fabric
)允许您通过利用最好的python和bash来创建任意复杂的命令。
还有几个nice python -m
one-liners例如:
$ python3 -m http.server # serve current directory over http
$ python -m zipfile # work with zipfiles
$ python -m calendar # show calendar
$ python -m telnetlib towel.blinkenlights.nl # Star Wars