Ist es möglich, unter Code zu ändern Ausdruck von 'stdout' zu haben und 'stderr':subprocess.Popen: Klonen von stdout und stderr sowohl an Terminal und Variablen
- auf dem Terminal gedruckt (real Zeit),
- und schließlich gespeichert in outs und Fehler Variablen?
Der Code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import subprocess
def run_cmd(command, cwd=None):
p = subprocess.Popen(command, cwd=cwd, shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
outs, errs = p.communicate()
rc = p.returncode
outs = outs.decode('utf-8')
errs = errs.decode('utf-8')
return (rc, (outs, errs))
Dank besonderer Dank geht an @unutbu, für @ jf-sebastian, letzte Funktion:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from queue import Queue
from subprocess import PIPE, Popen
from threading import Thread
def read_output(pipe, funcs):
for line in iter(pipe.readline, b''):
for func in funcs:
func(line.decode('utf-8'))
pipe.close()
def write_output(get):
for line in iter(get, None):
sys.stdout.write(line)
def run_cmd(command, cwd=None, passthrough=True):
outs, errs = None, None
proc = Popen(
command,
cwd=cwd,
shell=False,
close_fds=True,
stdout=PIPE,
stderr=PIPE,
bufsize=1
)
if passthrough:
outs, errs = [], []
q = Queue()
stdout_thread = Thread(
target=read_output, args=(proc.stdout, [q.put, outs.append])
)
stderr_thread = Thread(
target=read_output, args=(proc.stderr, [q.put, errs.append])
)
writer_thread = Thread(
target=write_output, args=(q.get,)
)
for t in (stdout_thread, stderr_thread, writer_thread):
t.daemon = True
t.start()
proc.wait()
for t in (stdout_thread, stderr_thread):
t.join()
q.put(None)
outs = ' '.join(outs)
errs = ' '.join(errs)
else:
outs, errs = proc.communicate()
outs = '' if outs == None else outs.decode('utf-8')
errs = '' if errs == None else errs.decode('utf-8')
rc = proc.returncode
return (rc, (outs, errs))
Das Codebeispiel speichert 'outs' und "Fehler" und gibt sie zurück ... Um auf dem Terminal zu drucken, einfach "wenn outs: Ausdrucke" 'irrs: print errs ' – bnlucas
@bnlucas Danke, aber wie ich im ersten Punkt sagte: die Ausgabe sollte in gedruckt werden ECHTZEIT zu Terminal, wie ohne PIPEing. –
Wenn Sie Python 3-Code benötigen; addiere [tag: python-3.x] tag (ich sehe python3 im shebang). Ihr Code wie geschrieben wird Lese-Threads hängen lassen. In Python 3 ist '' '' ein Unicode-Literal, aber 'pipe.readline()' gibt standardmäßig Bytes zurück ('''! = B" "'auf Python 3). Wenn Sie es reparieren, wird der Writer-Thread nicht enden, weil nichts "" "in die Warteschlange stellt. – jfs