我目前通过一堆不好记的AWK、sed、Bash和一小部分Perl来做我的文本文件操作。

我已经看到提到的一些地方,python很适合做这种事情。我如何使用Python来代替shell脚本,AWK, sed和朋友?


当前回答

在ShellPy库中可以使用python而不是bash。

下面是一个从Github下载Python用户头像的例子:

import json
import os
import tempfile

# get the api answer with curl
answer = `curl https://api.github.com/users/python
# syntactic sugar for checking returncode of executed process for zero
if answer:
    answer_json = json.loads(answer.stdout)
    avatar_url = answer_json['avatar_url']

    destination = os.path.join(tempfile.gettempdir(), 'python.png')

    # execute curl once again, this time to get the image
    result = `curl {avatar_url} > {destination}
    if result:
        # if there were no problems show the file
        p`ls -l {destination}
    else:
        print('Failed to download avatar')

    print('Avatar downloaded')
else:
    print('Failed to access github api')

如您所见,所有在grave重音(')符号内的表达式都在shell中执行。在Python代码中,您可以捕获此执行的结果并对其执行操作。例如:

log = `git log --pretty=oneline --grep='Create'

这一行首先在shell中执行git log——pretty=oneline——grep='Create',然后将结果赋值给log变量。结果具有以下属性:

从已执行进程的Stdout中Stdout整个文本

Stderr从已执行进程的Stderr得到的整个文本

Returncode执行的返回码

这是该库的总体概述,更详细的描述和示例可以在这里找到。

其他回答

Pythonpy是一个工具,可以方便地访问awk和sed的许多特性,但使用python语法:

$ echo me2 | py -x 're.sub("me", "you", x)'
you2

我在PyPI: ez上发布了一个包。 使用pip install ez进行安装。

它在shell中打包了通用命令,我的库使用了与shell基本相同的语法。例如,cp(源,目标)可以同时处理文件和文件夹!(书纸的包装。shutil副本。Copytree,它决定什么时候使用哪个)。更妙的是,它可以支持像R!

另一个例子:没有os。Walk,使用fls(path, regex)递归地查找文件并使用正则表达式进行过滤,它将返回带有或没有全路径的文件列表

最后一个例子:你可以结合它们来编写非常简单的脚本: Files = fls('.','py$');文件,myDir (cp)

一定要去看看!我花了几百个小时来编写/改进它!

任何shell都有几组特性。

The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python. And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess. The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly. The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python. Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing. The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.

特定的程序(awk、sed、grep等)通常可以被重写为Python模块。不要走极端。替换您需要的内容并改进“grep”模块。不要一开始就编写一个替换“grep”的Python模块。

最好的事情是你可以一步一步来做。

用Python替换AWK和PERL。不要管其他的事情。 看看用Python替换GREP。这可能有点复杂,但是您的GREP版本可以根据您的处理需求进行定制。 看看用使用os.walk的Python循环替换FIND。这是一个巨大的胜利,因为您不需要生成那么多的进程。 看看用Python脚本替换常见的shell逻辑(循环、决策等)。

最好的选择是专门针对您的问题的工具。如果它正在处理文本文件,那么Sed、Awk和Perl是最佳竞争者。Python是一种通用动态语言。与任何通用语言一样,它支持文件操作,但这不是它的核心目的。如果我特别需要一种动态语言,我会考虑Python或Ruby。

简而言之,非常好地学习Sed和Awk,以及所有其他随*nix风格而来的好东西(所有Bash内置,grep, tr等等)。如果您感兴趣的是文本文件处理,那么您已经使用了正确的方法。

如果您想使用Python作为shell,为什么不看看IPython呢?用互动的方式学习语言也很好。 如果需要进行大量的文本操作,并且使用Vim作为文本编辑器,那么还可以直接用python为Vim编写插件。只需在Vim中输入“:help python”,然后按照说明操作,或者看看这个演示文稿。它是如此简单和强大的编写函数,你将直接在你的编辑器中使用!