使用xterm打开新控制台:在当前控制台打印时,如何在新控制台也打印
我现在正在使用Python。我有一个线程代表我的整个程序。我想用os.system(xterm&)打开另一个控制台窗口,并且这个方法是有效的。唯一的问题是,我能否在一个线程向旧窗口打印的同时,向新窗口打印内容呢?
import sys
import os
def my_fork():
child_pid = os.fork()
if child_pid == 0:
function=open('SMITH747.txt','r')
f=function.readlines()
fd = open("output", "w")
# Open xterm window with logs from that file
p = subprocess.Popen(["xterm", "-e", "tail", "-f", "output"])
# Do logging
while(True):
for i in range(1):
fd.write("Hello, world!")
time.sleep(2)
if f==[]:
pass
else:
bud=False
fd.flush()
else:
function=open('SMITH747.txt','w')
var=input('Enter ')
if var=='q':
function.write('yo')
if __name__ == "__main__":
my_fork()
这是我现在的代码:它可以工作,但我无法让它读取我的文件,并在f不为空时终止。如果有人能帮我调试这一部分,我将非常感激。这样就完美了!
5 个回答
0
import os, subprocess, time, threading
# Reads commands from fifo in separate thread.
# if kill command is received, then down continue flag.
class Killer(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.continueFlag = True
def run(self):
fd=open('ipc','r')
command = fd.read()
if command == "kill\n":
self.continueFlag = False
def my_fork():
# create fifo for reliable inter-process communications
# TODO: check existence of fifo
os.mkfifo('ipc')
# Be careful with threads and fork
child_pid = os.fork()
if child_pid == 0:
fd = open("output", "w")
subprocess.Popen(["xterm", "-e", "tail", "-f", "output"])
# Create and start killer, be careful with threads and fork
killer = Killer()
killer.start()
# Perform work while continue flag is up
while(killer.continueFlag):
fd.write("Hello, world!\n")
fd.flush()
time.sleep(2)
# need to kill subprocess with opened xterm
else:
# File must be fifo, otherwise race condition is possible.
fd=open('ipc','w')
var=input('Enter ')
if var=='q':
fd.write('kill\n')
if __name__ == "__main__":
my_fork()
附言:讨论的内容离主题太远了,可能你应该换个话题。
0
你可以创建一个叫做命名管道的东西,让你新建的线程往里面写数据,然后再打开一个新的终端,运行 tail -f
来查看这个管道里的内容。
0
我想打开一个新的控制台窗口的原因是,我想在新的窗口里输入内容,比如 var=input('在这里输入 q: '),这样可以等待用户按下回车键,从而结束旧的线程...
我认为最简单的方法是写一个辅助脚本,让用户在一个单独的终端里输入内容。这并不是一些复杂的输入输出重定向技巧 :)
主程序文件 main.py:
import os
os.mkfifo("/tmp/1234");
os.system("xterm -e python input.py &")
f = open("/tmp/1234")
print(f.read())
输入程序文件 input.py:
var=input('Enter q here: ')
fifo = open('/tmp/1234','w')
fifo.write(str(var))
fifo.flush()