Код: Выделить всё
import os
import sys
import subprocess
pid = os.getpid()
def printer():
print(f"[Printer-{pid}] Startup!")
for line in sys.stdin:
print(f"[Printer-{pid}] {line.strip()}")
def launcher():
try:
print(f"\t[Launcher-{pid}] Sending initial message.")
# launches the "printer()" function in another process.
child = subprocess.Popen(
(sys.executable, __file__, "printer"),
stdin=subprocess.PIPE,
universal_newlines=True,
bufsize=1
)
child.stdin.write("Initial setup message!\n")
print(f"\t[Launcher-{pid}] Turning over control.")
for line in sys.stdin:
child.stdin.write(line)
finally:
child.kill()
child.communicate()
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == 'printer':
printer()
else:
launcher()
Код: Выделить всё
[Launcher-24132] Sending initial message.
[Launcher-24132] Turning over control.
[Printer-29572] Startup!
[Printer-29572] Initial setup message!
message from stdin
[Printer-29572] message from stdin
Код: Выделить всё
def launcher_alternate():
subprocess.Popen((sys.executable, __file__, "printer"))
sys.exit(0)
С сообщением «начальная настройка» возникает ряд проблем:
- Родительский процесс должен оставаться рядом для пересылки сообщений.
- Мы удваиваем накладные расходы ядра на передачу данных по каналам.
- Нам нужно сделать предположения о как мы хотим, чтобы наши потоки буферизовались.
Код: Выделить всё
# DOES NOT EXIST (I think.)
os.splice(sys.stdin, child.stdin)
Подробнее здесь: https://stackoverflow.com/questions/790 ... s-together