我目前通过一堆不好记的AWK、sed、Bash和一小部分Perl来做我的文本文件操作。
我已经看到提到的一些地方,python很适合做这种事情。我如何使用Python来代替shell脚本,AWK, sed和朋友?
我目前通过一堆不好记的AWK、sed、Bash和一小部分Perl来做我的文本文件操作。
我已经看到提到的一些地方,python很适合做这种事情。我如何使用Python来代替shell脚本,AWK, sed和朋友?
当前回答
添加到前面的答案:检查pexpect模块处理交互式命令(adduser, passwd等)
其他回答
添加到前面的答案:检查pexpect模块处理交互式命令(adduser, passwd等)
以下是我的一些经验之谈:
外壳:
Shell可以很容易地生成只读代码。把它写下来,当你回头看的时候,你永远也不会知道你又做了什么。这很容易做到。 shell可以用管道在一行中做大量的文本处理、分割等。 当涉及到集成不同编程语言的程序调用时,它是最好的粘合语言。
python:
如果你想要Windows的可移植性,请使用python。 当您必须处理的不仅仅是文本,比如数字的集合时,Python可能会更好。为此,我推荐python。
我通常选择bash来处理大多数事情,但当我有一些必须跨越窗口边界的东西时,我就使用python。
我已经构建了半长的shell脚本(300-500行)和Python代码,它们具有类似的功能。当执行许多外部命令时,我发现shell更容易使用。当有大量文本操作时,Perl也是一个很好的选择。
Pythonpy是一个工具,可以方便地访问awk和sed的许多特性,但使用python语法:
$ echo me2 | py -x 're.sub("me", "you", x)'
you2
我刚刚发现了如何结合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。