python - 如何在Linux命令中使用Python

标签 python linux awk

我习惯于编写大量 AWK 命令,但是,总是想使用 Python 来完成与 Awk 相同的操作而无需编写 .py 文件。我有 Python 基础知识,但没有命令行知识。

例如,我有以下 AWK 命令。 python 的等价物是什么?

awk '/Classic.java/ {print $0}' somefile.log;

最佳答案

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 (受到推崇的)。或者,如果您想要更多类似 BASHwards 的语法和子进程命令的制表符补全;尝试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

关于python - 如何在Linux命令中使用Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841676/

相关文章:

linux - 比较不同机器之间的时间戳

bash - awk 子替换中的奇怪行为

awk - 如何仅从每一列的一行中的第一个单词中删除特定字符?

bash - 在 AWK 表达式中使用 bash 变量

python - docker 无法访问主机中的gunicorn 服务的资源

python - 当我尝试将我的 numpy 数组保存到 .npy 文件时,出现内存错误。如何从内存有限的图像文件创建一个大的 .npy 文件?

python - 使用pydrive从google share drive下载文件,文件存在,但API返回404 File not found错误

python - python UPDATE 命令中的 0L 或 1L 错误

sql-server - Linux Ubuntu 14.04 : wrong library version 上的 Microsoft SQL Server ODBC 驱动程序

linux - Telnet 到嵌入式 linux 板 : command not found