gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:58 25 4
gpt4 key购买 nike

我习惯于编写大量 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com