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

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


当前回答

我刚刚发现了如何结合bash和ipython的最佳部分。到目前为止,这似乎比使用subprocess等更舒服。你可以很容易地复制现有bash脚本的大部分内容,例如以python的方式添加错误处理:) 这是我的结果:

#!/usr/bin/env ipython3

# *** How to have the most comfort scripting experience of your life ***
# ######################################################################
#
# … by using ipython for scripting combined with subcommands from bash!
#
# 1. echo "#!/usr/bin/env ipython3" > scriptname.ipy    # creates new ipy-file
#
# 2. chmod +x scriptname.ipy                            # make in executable
#
# 3. starting with line 2, write normal python or do some of
#    the ! magic of ipython, so that you can use unix commands
#    within python and even assign their output to a variable via
#    var = !cmd1 | cmd2 | cmd3                          # enjoy ;)
#
# 4. run via ./scriptname.ipy - if it fails with recognizing % and !
#    but parses raw python fine, please check again for the .ipy suffix

# ugly example, please go and find more in the wild
files = !ls *.* | grep "y"
for file in files:
  !echo $file | grep "p"
# sorry for this nonsense example ;)

请参阅IPython文档,了解系统shell命令并将其用作系统shell。

其他回答

我建议你看一本很棒的在线书籍Dive Into Python。这就是我最初学习这门语言的方式。

除了教你语言的基本结构和大量有用的数据结构之外,它还有一个关于文件处理的很好的章节,以及关于正则表达式等的后续章节。

截至2015年和Python 3.4的发布,现在有一个相当完整的用户交互shell: http://xon.sh/或https://github.com/scopatz/xonsh

演示视频没有显示正在使用的管道,但是在默认shell模式下支持管道。

Xonsh(“conch”)非常努力地模仿bash,因此您已经获得了肌肉记忆,例如

env | uniq | sort -r | grep PATH

or

my-web-server 2>&1 | my-log-sorter

仍然可以正常工作。

本教程相当冗长,似乎涵盖了人们通常在ash或bash提示符时所期望的大量功能:

Compiles, Evaluates, & Executes! Command History and Tab Completion Help & Superhelp with ? & ?? Aliases & Customized Prompts Executes Commands and/or *.xsh Scripts which can also be imported Environment Variables including Lookup with ${} Input/Output Redirection and Combining Background Jobs & Job Control Nesting Subprocesses, Pipes, and Coprocesses Subprocess-mode when a command exists, Python-mode otherwise Captured Subprocess with $(), Uncaptured Subprocess with $[], Python Evaluation with @() Filename Globbing with * or Regular Expression Filename Globbing with Backticks

以下是我的一些经验之谈:

外壳:

Shell可以很容易地生成只读代码。把它写下来,当你回头看的时候,你永远也不会知道你又做了什么。这很容易做到。 shell可以用管道在一行中做大量的文本处理、分割等。 当涉及到集成不同编程语言的程序调用时,它是最好的粘合语言。

python:

如果你想要Windows的可移植性,请使用python。 当您必须处理的不仅仅是文本,比如数字的集合时,Python可能会更好。为此,我推荐python。

我通常选择bash来处理大多数事情,但当我有一些必须跨越窗口边界的东西时,我就使用python。

任何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逻辑(循环、决策等)。

如果你的文本文件操作通常是一次性的,可能在shell提示符下完成,你从python中不会得到更好的东西。

另一方面,如果你经常不得不一遍又一遍地做同样的(或类似的)任务,并且你必须为此编写脚本,那么python是很棒的——你可以很容易地创建自己的库(你也可以用shell脚本来做,但它更麻烦)。

这是一个很简单的例子。

import popen2
stdout_text, stdin_text=popen2.popen2("your-shell-command-here")
for line in stdout_text:
  if line.startswith("#"):
    pass
  else
    jobID=int(line.split(",")[0].split()[1].lstrip("<").rstrip(">"))
    # do something with jobID

还要检查sys和getopt模块,它们是您首先需要的。