如何在Linux命令中使用Python

2024-06-05 23:40:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我习惯于编写很多AWK命令,但是,我一直希望使用Python来完成与AWK相同的工作,而不必编写.py文件。我有Python的基础知识,但在命令行中没有。你知道吗

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

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

Tags: 文件命令行py命令logjavasomefileprint
1条回答
网友
1楼 · 发布于 2024-06-05 23:40:30

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))'

另一种选择是使用^{} as a shell或基于浏览器的notebook(推荐)。或者,如果您希望子流程命令的语法和制表符更为简单,请尝试^{} 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

^{} and its alternatives (^{}, ^{}, ^{}, ^{} (module), ^{})允许您利用python和bash的优点创建任意复杂的命令。你知道吗

还有几个nice ^{} 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

相关问题 更多 >