问题描述
我正在使用以下 python 代码在 Tkinter 窗口中嵌入终端窗口(来自 Ubuntu Linux).我想在终端窗口启动时自动在窗口中给出命令sh kBegin":
I'm using the following python code to embed a terminal window (from Ubuntu Linux) in a Tkinter window. I would like give the command 'sh kBegin' in the window automatically when the terminal window starts:
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##
我怎样才能让它工作?
推荐答案
您可以通过在伪终端从子节点中写入来与 shell 进行交互.这是它如何工作的演示.这个答案在某种程度上基于对Linux 伪终端:在另一个终端中执行从一个终端发送的字符串.
You can interact with a shell by writing in the pseudo-terminal slave child. Here is a demo of how it could works. This answer is somewhat based on an answer to Linux pseudo-terminals: executing string sent from one terminal in another.
重点是获取 xterm 使用的伪终端(通过 tty
命令)并将您的方法的输出和输入重定向到这个伪终端文件.例如 ls /dev/pts/1
The point is to get the pseudo-terminal used by xterm (through tty
command) and redirect output and input of your method to this pseudo-terminal file. For instance ls < /dev/pts/1 > /dev/pts/1 2> /dev/pts/1
注意
- xterm 子进程被泄露(不推荐使用
os.system
,尤其是&
指令.见suprocess
模块). - 可能无法以编程方式找到使用的 tty
- 每个命令都在一个新的suprocess中执行(只显示输入和输出),所以状态修改命令如
cd
不起作用,以及xterm的上下文(cd
在 xterm 中)
- xterm child processed are leaked (the use of
os.system
is not recommended, especially for&
instructions. Seesuprocess
module). - it may not be possible to find programmatically which tty is used
- each commands are executed in a new suprocess (only input and output is displayed), so state modification command such as
cd
have no effect, as well as context of the xterm (cd
in the 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()
这篇关于在嵌入式终端中发出命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!