我正在使用以下python代码在Tkinter窗口中嵌入一个终端窗口(来自Ubuntu Linux)。当终端窗口启动时,我想在窗口中自动发出命令'sh kBegin':
from Tkinter import *
from os import system as cmd
root = Tk()
termf = Frame(root, height=800, width=1000)
termf.pack(fill=BOTH, expand=YES)
wid = termf.winfo_id()
cmd('xterm -into %d -geometry 160x50 -sb &' % wid)
root.mainloop()
伪:
cmd('xterm -into %d -geometry 160x50 -sb &' % wid)
embedded_terminal('sh kBegin')
# EMBEDDED TERMINAL DISPLAYS OUTPUT OF sh kBegin##
我如何才能使这个工作?
答案 0 :(得分:6)
您可以通过写入伪终端从属子进程与shell进行交互。这是一个如何工作的演示。这个答案有点基于Linux pseudo-terminals: executing string sent from one terminal in another的答案。
重点是获取xterm(通过tty
命令)使用的伪终端,并将方法的输出和输入重定向到此伪终端文件。例如ls < /dev/pts/1 > /dev/pts/1 2> /dev/pts/1
请注意
os.system
,尤其是&
指令。请参阅suprocess
module)。cd
)不起作用,以及xterm的上下文(cd
的xterm)
from Tkinter import *
from os import system as cmd
root = Tk()
termf = Frame(root, height=700, width=1000)
termf.pack(fill=BOTH, expand=YES)
wid = termf.winfo_id()
f=Frame(root)
Label(f,text="/dev/pts/").pack(side=LEFT)
tty_index = Entry(f, width=3)
tty_index.insert(0, "1")
tty_index.pack(side=LEFT)
Label(f,text="Command:").pack(side=LEFT)
e = Entry(f)
e.insert(0, "ls -l")
e.pack(side=LEFT,fill=X,expand=1)
def send_entry_to_terminal(*args):
"""*args needed since callback may be called from no arg (button)
or one arg (entry)
"""
command=e.get()
tty="/dev/pts/%s" % tty_index.get()
cmd("%s <%s >%s 2> %s" % (command,tty,tty,tty))
e.bind("<Return>",send_entry_to_terminal)
b = Button(f,text="Send", command=send_entry_to_terminal)
b.pack(side=LEFT)
f.pack(fill=X, expand=1)
cmd('xterm -into %d -geometry 160x50 -sb -e "tty; sh" &' % wid)
root.mainloop()