我想通过Python脚本调用' sort‘命令对以制表符分隔的文件进行排序。如果我使用这个:
subprocess.Popen(["sort", r"-t$'t'", "-k1,2", "input", "-o", "output"]).wait()我得到了这个错误:
sort: multi-character tab `$\'t\''如果我使用shell=True
subprocess.Popen(["sort", r"-t$'t'", "-k1,2", "input", "-o", "output"], shell=True).wait()这个过程就会挂起。
我更喜欢使用第一种方法,没有shell=True。有什么建议吗?
编辑:文件很大。
发布于 2013-06-07 03:58:40
Python可以创建带有选项卡的字符串;只有当您直接在shell中工作时,才需要使用$'\t'。
subprocess.Popen(["sort", "-t\t", "-k1,2", "input", "-o", "output"]).wait()发布于 2013-06-07 04:11:14
subprocess.call(r"sort -t\t -k1,2 input -o output")
看起来更干净-- call是子进程模块中比“on”更高级别的函数--并且会让你的代码更易读。
那么,很可能,当调用一个外部的"sort“时,可能会有一些处理大文件的工具(>可用内存的ammout )--除非你是在处理这些文件,否则你很可能就错了。
与shell脚本不同,Python是自包含的,因为它可以在内部对数据执行大多数任务,而不是通过外部简单的posix程序传递数据。
要对名为"input“的文件进行排序并将结果保存到内存中,只需执行以下操作:
# read the data into a list, one line per item:
data = open("input", "rt").readlines()
# sort it, splitting the line on tab characters and taking the first two as key:
data.sort(key=lambda line: line.split("\t")[:2]
# and "data" contains a sorted list of your lineshttps://stackoverflow.com/questions/16971054
复制相似问题