【问题标题】:sort and uniq in pythonpython中的排序和uniq
【发布时间】:2014-07-22 15:32:37
【问题描述】:

我想在 python 中执行一些 shell 命令。我有一个 main.py,它调用连续函数,我发现其中一些更容易在 shell 中完成。问题:我想自动完成所有这些!

我想做这样的代码:

sort fileIn | uniq > fileOut

我的问题是用管道字符来做。我试试:

from subprocess import call
call(['sort ',FileOut,'|',' uniq '])

 p1 = subprocess.Popen(['sort ', FileOut], stdout=subprocess.PIPE)
p2 = subprocess.Popen([" wc","-l"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output,err = p2.communicate()

但这一切都不起作用。 (注意:FileOut 是一个字符串)

【问题讨论】:

  • 如果我删除'sort ' 之后和" wc" 之前的多余空格,第二个示例对我来说效果很好。
  • 您可能对plumbumshell,甚至是内置的pipes模块感兴趣。

标签: python shell sorting


【解决方案1】:

您需要使用shell=True,这会使您的命令由shell 运行,而不是使用exec 系统调用:

call('sort {0} | uniq'.format(FileOut), shell=True)

值得注意的是,如果您只是想要 python 中文件的唯一行(没有特定顺序),那么没有 shell 可能会更容易:

unique_lines= set(open('filename').readlines())

【讨论】:

  • 请注意,您应该只使用带有可信输入的shell=True,否则会带来安全风险。
  • @dano 我认为运行从不受信任的输入命名的进程总是不安全的,shell=True 或其他。 shell=False 仅保护您免受攻击者在您只期望一个参数时伪造多个参数。
  • @goncalopp shell=True 可以让攻击者运行任意命令。 shell=False 不可能做到这一点。例如,如果 FileOut"& touch uhoh.txt",则运行该命令将导致创建 uhoh.txt(至少在 Linux 上)。
  • set 可以使用可迭代对象进行初始化,因此 set(open('filename')) 就足够了。不过我会做with open('filename') as f: unique_lines = set(f)
【解决方案2】:

我厌倦了总是查找 Popen 模块文档,所以这是我用来包装 Popen 的实用程序函数的精简版。您可以将第一次调用的 so 参数作为输入传递给下一次调用。如果需要,您还可以进行错误检查/解析。

def run(command, input=None)
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, shell=True)
    if input:
        so, se = process.communicate(input)
    else:
        so, se = process.communicate()
    rc = process.returncode
    return so, se, rc

【讨论】:

  • check_output,在 2.7 中引入,在这方面有很大帮助,尽管您的版本在某些情况下可能更有用
猜你喜欢
  • 2011-09-13
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多