我正在尝试使用此命令生成随机字符串:
字符串/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()
此外,strings
ing 然后 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/