我正在编写一个脚本,有两种不同的输出,称为Op1和Op2。我想将Op1输出到调用Python进程的终端上,而Op2应该被转储到另一个终端实例中。我能做到吗?即使答案是针对Linux特定的,也没关系,我需要一个临时解决方案。
你可以使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
以下是一些Linux的常用解决方案。
为了实现这个目标,通常需要两个程序。
文件读写+循环:
套接字(管道):
文件读写+信号:
顺便说一下,我认为您的要求不需要编写任何守护进程程序,因为您肯定有两个控制台。
此外,我非常确定在特定控制台上打印信息是可行的。
第二种解决方案[套接字]的示例:
# 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
作为对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()