我有python程序main.py
import subprocess
p = subprocess.Popen(
"/usr/bin/gnome-terminal -x 'handler.py'",
shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
p.stdin.write('Text sent to handler for display\n')
其中handler.py是
#!/usr/bin/python
print "In handler..."
程序main.py打开一个新的gnome-terminal并运行handler.py来显示“In handler ...”。如何让handler.py接收并打印从main.py发送的“发送到处理程序以供显示的文本”?
问题“Sending strings between python scripts”提供的答案就是我所追求的内容,其中handler.py在main.py创建的终端会话中运行。
答案 0 :(得分:1)
您可以将处理程序更改为从命令行而不是stdin
给出的文件中读取:
#!/usr/bin/env python
import shutil
import sys
import time
print "In handler..."
with open(sys.argv[1], 'rb') as file:
shutil.copyfileobj(file, sys.stdout)
sys.stdout.flush()
time.sleep(5)
然后你可以在main.py
中创建一个命名管道来发送数据:
#!/usr/bin/env python
import os
from subprocess import Popen
fifo = "fifo"
os.mkfifo(fifo)
p = Popen(["gnome-terminal", "-x", "python", "handler.py", fifo])
with open(fifo, 'wb') as file:
file.write("Text sent to handler for display")
os.remove(fifo)
p.wait()