【发布时间】:2014-04-11 12:45:35
【问题描述】:
我正在尝试在 wxPython 中创建一个 cmd,它的执行类似于 windows 上的 cmd,它具有相同的功能,但我也可以在其中添加我自己的命令。 我试过这段代码,但它给了我所有类型的警告和错误:
import wx
import subprocess
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.prompt = "user@stackOvervlow:~ "
self.textctrl = wx.TextCtrl(self, -1, '', style=wx.TE_PROCESS_ENTER|wx.TE_MULTILINE)
self.default_txt = self.textctrl.GetDefaultStyle()
self.textctrl.AppendText(self.prompt)
self.__set_properties()
self.__do_layout()
self.__bind_events()
def __bind_events(self):
self.Bind(wx.EVT_TEXT_ENTER, self.__enter)
def __enter(self, e):
self.value = (self.textctrl.GetValue())
self.eval_last_line()
e.Skip()
def __set_properties(self):
self.SetTitle("Poor Man's Terminal")
self.SetSize((800, 600))
self.textctrl.SetFocus()
def __do_layout(self):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(self.textctrl, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
self.Layout()
def eval_last_line(self):
nl = self.textctrl.GetNumberOfLines()
ln = self.textctrl.GetLineText(nl-1)
ln = ln[len(self.prompt):]
args = ln.split(" ")
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
retvalue = proc.communicate()[0]
c = wx.Colour(239, 177, 177)
tc = wx.TextAttr(c)
self.textctrl.SetDefaultStyle(tc)
self.textctrl.AppendText(retvalue)
self.textctrl.SetDefaultStyle(self.default_txt)
self.textctrl.AppendText(self.prompt)
self.textctrl.SetInsertionPoint(GetLastPosition() - 1)
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
我在 wxPython 中需要这个,因为我还想在 cmd 旁边创建按钮。我怎样才能创建这个?谢谢
【问题讨论】:
-
您指的是哪些错误和警告?除了几个弃用警告之外,您的代码对我来说运行没有错误。
-
@GreenAsJade 如果我运行像“echo hello”这样的命令,它可以正常工作,但如果我再次尝试运行它,我会收到此错误(我知道我正在正确执行命令:Traceback(最近一次调用最后):文件“C:\Python27\cmdtest.py”,第 26 行,在 输入 self.eval_last_line() 文件“C:\Python27\cmdtest.py”,第 47 行,在 eval_last_line proc = subprocess.Popen (args, stdout=subprocess.PIPE) 文件“C:\Python27\lib\subprocess.py”,第 709 行,在 __init errread, errwrite) 文件“C:\Python27\lib\subprocess.py”,第 957 行,在 _execute_child 启动信息中)WindowsError:[错误 87] 参数不正确
-
有趣。我根本无法使用您的代码运行命令。你是怎么做到的?
标签: python python-2.7 command wxpython command-prompt