【问题标题】:Getting output of system commands that use pipes (Python)获取使用管道的系统命令的输出(Python)
【发布时间】:2011-08-17 05:01:31
【问题描述】:

我正在尝试使用以下命令生成一个随机字符串:

strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n';

工作正常,但是当我尝试执行 subprocess.call(cmd,shell=True) 时,它只会卡在字符串 /dev/urandom 命令上,并使用 grep: writing output: Broken pipe 向我的屏幕发送垃圾邮件

这是什么原因造成的,我该如何解决?

【问题讨论】:

  • 如果将executable = '/bin/bash' 明确添加到call 会怎样?

标签: python linux pipe


【解决方案1】:

不需要子进程,观察:

>>> import base64
>>> r = open("/dev/urandom","r")
>>> base64.encodestring(r.read(22))[:30]
'3Ttlx6TT3siM8h+zKm+Q6lH1k+dTcg'
>>> r.close()

另外,stringsing 和 greping 来自/dev/urandom 的字母数字字符非常效率低下,并且浪费了大量的随机性。在我的台式电脑上,上面的 python 从 bash 执行的时间不到 10 毫秒,你的 strings ... oneliner 需要 300-400...

对于一个纯 python 解决方案,它也适用于没有 /dev/urandom 的系统 - 并且只给出字母数字字符(如果你真的不想要 + 或 /):

import string
import random
''.join([random.choice(string.printable[:62]) for i in range(30)])

【讨论】:

    【解决方案2】:

    首先,对于你正在做的事情,最好直接使用python生成字符串。

    无论如何,当使用subprocess 时,将数据从一个进程传送到另一个进程的正确方法是将stdout 和/或stderr 重定向到subprocess.PIPE,并将新进程的stdin 与上一个进程'stdout

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多