python - 获取使用管道的系统命令的输出 (Python)

标签 python linux pipe

我正在尝试使用此命令生成随机字符串:

字符串/dev/urandom | grep -o '[[:alnum:]]' |头-n 30 | tr -d '\n';

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

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

最佳答案

不需要子进程,观察:

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

此外,stringsing 然后 grep 来自 /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)])

关于python - 获取使用管道的系统命令的输出 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7088175/

相关文章:

c++ - 使用 select 多路复用未命名管道和其他文件描述符

linux - bash 标准输出无法重定向到文件

Python urllib2 http -1 错误

python - 如何在 Plone 中生成自定义 403 HTTP 响应(防止重定向)

python - 为什么 scipy.linalg 的方法在 9x9 矩阵上运行速度较慢?

php - Python SOAP 客户端、授权

linux - 带有项目列表的 makefile 过程变量,其中一项是带空格的引号字符串

sql - 如何在只有 1 个连接的 bash 循环中运行多个 sqlplus 查询

linux - 如何在 bash 中读取两个输入值?

c - 如何通过同一个管道向多个进程发送消息? (C语言)