【发布时间】:2017-12-22 12:08:11
【问题描述】:
我已经尝试使用以下实现提到here 的方法:
from subprocess import PIPE, Popen
process = Popen(['/usr/bin/openssl', 'enc', '-aes-256-cbc', '-a', '-pass', 'pass:asdf'], stdin=PIPE, stdout=PIPE)
process.stdin.write('Hello this is it')
process.stdin.flush()
print(repr(process.stdout.readline()))
但它卡在 readline() 虽然我已经写过并刷新了。我还尝试了提到here 的非阻塞方法,但这也阻塞了 readline()。以下是我后一种方法的代码:
import sys
import time
from subprocess import PIPE, Popen
from threading import Thread
from Queue import Queue, Empty
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
def write_to_stdin(process):
process.stdin.write(b'Hello this is it')
p = Popen(['/usr/bin/openssl', 'enc', '-aes-256-cbc', '-a', '-pass', 'pass:asdf'], stdin=PIPE, stdout=PIPE, bufsize=-1, close_fds=ON_POSIX)
q = Queue()
t2 = Thread(target=write_to_stdin, args=(p,))
t2.daemon = True
t2.start()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
try:
line = q.get(timeout=3) # or q.get(timeout=.1)
except Empty:
print('no output yet')
else:
print line
我得到没有输出作为输出。
唯一有效的方法是使用:
process.communicate
但这会关闭进程,我们必须再次重新打开进程。对于要加密的大量消息,这需要花费太多时间,我试图避免包含任何外部包来完成此任务。任何帮助将不胜感激谢谢。
【问题讨论】:
-
请也标记 Python。
-
添加了 Python 标签。
标签: python linux python-2.7 openssl aes