使用Python将输出发送到两个不同的控制台

7
我正在编写一个脚本,有两种不同的输出,称为Op1和Op2。我想将Op1输出到调用Python进程的终端上,而Op2应该被转储到另一个终端实例中。我能做到吗?即使答案是针对Linux特定的,也没关系,我需要一个临时解决方案。

尝试将其转储到文本文件中,而不是直接输出 - sameera sy
如果有帮助的话,只需正常打印脚本输出并通过tee命令将其分叉到多个输出流中。 - plamut
3个回答

8

你可以使Python脚本写入文件或将其输出导入到文件 python script.py >> output.log,然后你可以使用-f选项使用tail查看该文件,在控制台上连续更新视图。

代码片段示例

# logmaker.py
import time
import datetime

buffer_size = 0 # This makes it so changes appear without buffering
with open('output.log', 'a', buffer_size) as f:
    while(True):
        f.write('{}\n'.format(datetime.datetime.now()))
        time.sleep(1)

运行该文件。
python logmaker.py

接下来在一个或多个控制台中执行以下命令:

tail -f output.log

或者如果你更喜欢,可以使用less

less +F output.log

你应该像这样持续更新。
2016-07-06 10:52:44.997416
2016-07-06 10:52:45.998544
2016-07-06 10:52:46.999697

1
代码片段有帮助!谢谢。 - axolotl

2

以下是一些Linux的常用解决方案。

为了实现这个目标,通常需要两个程序。

文件读写+循环:

  1. 主程序+文件写入器(打印Op1并将Op2写入A文件)
  2. 文件读取器(持续获取A文件,直到其被修改,并打印A文件的内容)

套接字(管道):

  1. 主程序+发送器(打印Op1并将Op2发送到特定套接字)
  2. 接收器(监听特定套接字,在接收时打印Op2)

文件读写+信号:

  1. 主程序+文件写入器+信号发送器(打印Op1并将Op2写入文件A并向守护进程接收器发送信号)
  2. 信号接收器(等待接收信号并打印文件A的内容)

顺便说一下,我认为您的要求不需要编写任何守护进程程序,因为您肯定有两个控制台。

此外,我非常确定在特定控制台上打印信息是可行的。


第二种解决方案[套接字]的示例:

# print1.py (your main program)
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
sock.connect(('localhost', 8001))  
Op1 = 'Op1'
Op2 = 'Op2'
print Op1 
sock.send(Op2)  
sock.close()

步骤

// a. console 2: listen 8001 port
// Luckily, nc(netcat) is enough to finish this without writing any code.
$ nc -l 8001

// b. console 1: run your main program
$ python print1.py
Op1

// c. console 2
Op2

1

作为对Kir回答上面的跟进,因为我正在处理类似的东西,所以我进一步修改了脚本,使用线程使控制台监听直接从脚本启动,而不必手动启动。希望这有所帮助。

import subprocess
import threading
import socket
import time

def listenproc():
 monitorshell = subprocess.Popen("mate-terminal --command=\"nc -l 8001\"",shell=True)

def printproc():
 print("Local message")
 time.sleep(5) # delay sending of message making sure port is listening
 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 sock.connect(('localhost', 8001))
 sock.send("Sent message")
 time.sleep(5)
 sock.close()

listenthread = threading.Thread(name="Listen", target=listenproc, args=())
printhread = threading.Thread(name="Print", target=printproc, args=())

listenthread.start()
printhread.start()
listenthread.join()
printhread.join()

osbornere,你的解决方案看起来非常有趣,我仍在努力理解它。 'mate-terminal' 不被识别为内部或外部命令, - JDOaktown
什么是“mate-terminal”? - JDOaktown
我正在使用Windows 64位操作系统运行Python 3.7.1版。 - JDOaktown
mate-terminal 是 MATE 桌面环境的终端(https://mate-desktop.org/)。实现这个功能已经过了一段时间,我不记得是否使用 mate-terminal 是出于特定原因还是只是因为我所使用的机器上已经安装了 MATE。 - osbornere

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接