在嵌入式终端中下达命令

2024-10-01 15:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的python代码在Tkinter窗口中嵌入一个终端窗口(来自ubuntulinux)。当终端窗口启动时,我想在窗口中自动发出命令'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()

伪码:

^{pr2}$

我该怎么做?在


Tags: 代码fromimport命令cmd终端ostkinter
1条回答
网友
1楼 · 发布于 2024-10-01 15:49:28

可以通过编写伪终端从属子对象来与shell交互。下面是一个如何工作的演示。{答案基于这个。在

关键是获取xterm使用的伪终端(通过tty命令),并将方法的输出和输入重定向到这个伪终端文件。例如ls < /dev/pts/1 > /dev/pts/1 2> /dev/pts/1

请注意

  1. 处理的xterm child被泄漏(不建议使用os.system,尤其是&指令。见^{} module)。在
  2. 可能无法通过编程方式找到使用哪个tty
  3. 每个命令都在一个新的supprocess中执行(只显示输入和输出),因此状态修改命令(如cd)以及xterm的上下文(xterm中的cd)无效

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()

相关问题 更多 >

    热门问题