gconsole.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. """
  2. @package core.gconsole
  3. @brief Command output widgets
  4. Classes:
  5. - goutput::CmdThread
  6. - goutput::GStdout
  7. - goutput::GStderr
  8. - goutput::GConsole
  9. (C) 2007-2014 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Michael Barton (Arizona State University)
  13. @author Martin Landa <landa.martin gmail.com>
  14. @author Vaclav Petras <wenzeslaus gmail.com> (refactoring)
  15. @author Anna Kratochvilova <kratochanna gmail.com> (refactoring)
  16. """
  17. import os
  18. import sys
  19. import re
  20. import time
  21. import threading
  22. import Queue
  23. import codecs
  24. import locale
  25. import wx
  26. from wx.lib.newevent import NewEvent
  27. import grass.script as grass
  28. from grass.script import task as gtask
  29. from grass.pydispatch.signal import Signal
  30. from core import globalvar
  31. from core.gcmd import CommandThread, GError, GException
  32. from core.utils import _
  33. from gui_core.forms import GUI
  34. from core.debug import Debug
  35. from core.settings import UserSettings
  36. from core.giface import Notification
  37. from gui_core.widgets import FormNotebook
  38. wxCmdOutput, EVT_CMD_OUTPUT = NewEvent()
  39. wxCmdProgress, EVT_CMD_PROGRESS = NewEvent()
  40. wxCmdRun, EVT_CMD_RUN = NewEvent()
  41. wxCmdDone, EVT_CMD_DONE = NewEvent()
  42. wxCmdAbort, EVT_CMD_ABORT = NewEvent()
  43. wxCmdPrepare, EVT_CMD_PREPARE = NewEvent()
  44. def GrassCmd(cmd, env=None, stdout=None, stderr=None):
  45. """Return GRASS command thread"""
  46. return CommandThread(cmd, env=env,
  47. stdout=stdout, stderr=stderr)
  48. class CmdThread(threading.Thread):
  49. """Thread for GRASS commands"""
  50. requestId = 0
  51. def __init__(self, receiver, requestQ=None, resultQ=None, **kwds):
  52. """
  53. :param receiver: event receiver (used in PostEvent)
  54. """
  55. threading.Thread.__init__(self, **kwds)
  56. if requestQ is None:
  57. self.requestQ = Queue.Queue()
  58. else:
  59. self.requestQ = requestQ
  60. if resultQ is None:
  61. self.resultQ = Queue.Queue()
  62. else:
  63. self.resultQ = resultQ
  64. self.setDaemon(True)
  65. self.requestCmd = None
  66. self.receiver = receiver
  67. self._want_abort_all = False
  68. self.start()
  69. def RunCmd(self, *args, **kwds):
  70. """Run command in queue
  71. :param args: unnamed command arguments
  72. :param kwds: named command arguments
  73. :return: request id in queue
  74. """
  75. CmdThread.requestId += 1
  76. self.requestCmd = None
  77. self.requestQ.put((CmdThread.requestId, args, kwds))
  78. return CmdThread.requestId
  79. def GetId(self):
  80. """Get id for next command"""
  81. return CmdThread.requestId + 1
  82. def SetId(self, id):
  83. """Set starting id"""
  84. CmdThread.requestId = id
  85. def run(self):
  86. os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
  87. while True:
  88. requestId, args, kwds = self.requestQ.get()
  89. for key in ('callable', 'onDone', 'onPrepare', 'userData', 'addLayer', 'notification'):
  90. if key in kwds:
  91. vars()[key] = kwds[key]
  92. del kwds[key]
  93. else:
  94. vars()[key] = None
  95. if not vars()['callable']:
  96. vars()['callable'] = GrassCmd
  97. requestTime = time.time()
  98. # prepare
  99. if self.receiver:
  100. event = wxCmdPrepare(cmd=args[0],
  101. time=requestTime,
  102. pid=requestId,
  103. onPrepare=vars()['onPrepare'],
  104. userData=vars()['userData'])
  105. wx.PostEvent(self.receiver, event)
  106. # run command
  107. event = wxCmdRun(cmd=args[0],
  108. pid=requestId,
  109. notification=vars()['notification'])
  110. wx.PostEvent(self.receiver, event)
  111. time.sleep(.1)
  112. self.requestCmd = vars()['callable'](*args, **kwds)
  113. if self._want_abort_all and self.requestCmd is not None:
  114. self.requestCmd.abort()
  115. if self.requestQ.empty():
  116. self._want_abort_all = False
  117. self.resultQ.put((requestId, self.requestCmd.run()))
  118. try:
  119. returncode = self.requestCmd.module.returncode
  120. except AttributeError:
  121. returncode = 0 # being optimistic
  122. try:
  123. aborted = self.requestCmd.aborted
  124. except AttributeError:
  125. aborted = False
  126. time.sleep(.1)
  127. # set default color table for raster data
  128. if UserSettings.Get(group='rasterLayer',
  129. key='colorTable', subkey='enabled') and \
  130. args[0][0][:2] == 'r.':
  131. colorTable = UserSettings.Get(group='rasterLayer',
  132. key='colorTable',
  133. subkey='selection')
  134. mapName = None
  135. if args[0][0] == 'r.mapcalc':
  136. try:
  137. mapName = args[0][1].split('=', 1)[0].strip()
  138. except KeyError:
  139. pass
  140. else:
  141. moduleInterface = GUI(show=None).ParseCommand(args[0])
  142. outputParam = moduleInterface.get_param(value='output',
  143. raiseError=False)
  144. if outputParam and outputParam['prompt'] == 'raster':
  145. mapName = outputParam['value']
  146. if mapName:
  147. argsColor = list(args)
  148. argsColor[0] = ['r.colors',
  149. 'map=%s' % mapName,
  150. 'color=%s' % colorTable]
  151. self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
  152. self.resultQ.put((requestId, self.requestCmdColor.run()))
  153. if self.receiver:
  154. event = wxCmdDone(cmd=args[0],
  155. aborted=aborted,
  156. returncode=returncode,
  157. time=requestTime,
  158. pid=requestId,
  159. onDone=vars()['onDone'],
  160. userData=vars()['userData'],
  161. addLayer=vars()['addLayer'],
  162. notification=vars()['notification'])
  163. # send event
  164. wx.PostEvent(self.receiver, event)
  165. def abort(self, abortall=True):
  166. """Abort command(s)"""
  167. if abortall:
  168. self._want_abort_all = True
  169. if self.requestCmd is not None:
  170. self.requestCmd.abort()
  171. if self.requestQ.empty():
  172. self._want_abort_all = False
  173. class GStdout:
  174. """GConsole standard output
  175. Based on FrameOutErr.py
  176. Name: FrameOutErr.py
  177. Purpose: Redirecting stdout / stderr
  178. Author: Jean-Michel Fauth, Switzerland
  179. Copyright: (c) 2005-2007 Jean-Michel Fauth
  180. Licence: GPL
  181. """
  182. def __init__(self, receiver):
  183. """
  184. :param receiver: event receiver (used in PostEvent)
  185. """
  186. self.receiver = receiver
  187. def flush(self):
  188. pass
  189. def write(self, s):
  190. if len(s) == 0 or s == '\n':
  191. return
  192. for line in s.splitlines():
  193. if len(line) == 0:
  194. continue
  195. evt = wxCmdOutput(text=line + '\n',
  196. type='')
  197. wx.PostEvent(self.receiver, evt)
  198. class GStderr:
  199. """GConsole standard error output
  200. Based on FrameOutErr.py
  201. Name: FrameOutErr.py
  202. Purpose: Redirecting stdout / stderr
  203. Author: Jean-Michel Fauth, Switzerland
  204. Copyright: (c) 2005-2007 Jean-Michel Fauth
  205. Licence: GPL
  206. """
  207. def __init__(self, receiver):
  208. """
  209. :param receiver: event receiver (used in PostEvent)
  210. """
  211. self.receiver = receiver
  212. self.type = ''
  213. self.message = ''
  214. self.printMessage = False
  215. def flush(self):
  216. pass
  217. def write(self, s):
  218. if "GtkPizza" in s:
  219. return
  220. # remove/replace escape sequences '\b' or '\r' from stream
  221. progressValue = -1
  222. for line in s.splitlines():
  223. if len(line) == 0:
  224. continue
  225. if 'GRASS_INFO_PERCENT' in line:
  226. value = int(line.rsplit(':', 1)[1].strip())
  227. if value >= 0 and value < 100:
  228. progressValue = value
  229. else:
  230. progressValue = 0
  231. elif 'GRASS_INFO_MESSAGE' in line:
  232. self.type = 'message'
  233. self.message += line.split(':', 1)[1].strip() + '\n'
  234. elif 'GRASS_INFO_WARNING' in line:
  235. self.type = 'warning'
  236. self.message += line.split(':', 1)[1].strip() + '\n'
  237. elif 'GRASS_INFO_ERROR' in line:
  238. self.type = 'error'
  239. self.message += line.split(':', 1)[1].strip() + '\n'
  240. elif 'GRASS_INFO_END' in line:
  241. self.printMessage = True
  242. elif self.type == '':
  243. if len(line) == 0:
  244. continue
  245. evt = wxCmdOutput(text=line,
  246. type='')
  247. wx.PostEvent(self.receiver, evt)
  248. elif len(line) > 0:
  249. self.message += line.strip() + '\n'
  250. if self.printMessage and len(self.message) > 0:
  251. evt = wxCmdOutput(text=self.message,
  252. type=self.type)
  253. wx.PostEvent(self.receiver, evt)
  254. self.type = ''
  255. self.message = ''
  256. self.printMessage = False
  257. # update progress message
  258. if progressValue > -1:
  259. # self.gmgauge.SetValue(progressValue)
  260. evt = wxCmdProgress(value=progressValue)
  261. wx.PostEvent(self.receiver, evt)
  262. # Occurs when an ignored command is called.
  263. # Attribute cmd contains command (as a list).
  264. gIgnoredCmdRun, EVT_IGNORED_CMD_RUN = NewEvent()
  265. class GConsole(wx.EvtHandler):
  266. """
  267. """
  268. def __init__(self, guiparent=None, giface=None, ignoredCmdPattern=None):
  269. """
  270. :param guiparent: parent window for created GUI objects
  271. :param lmgr: layer manager window (TODO: replace by giface)
  272. :param ignoredCmdPattern: regular expression specifying commads
  273. to be ignored (e.g. @c '^d\..*' for
  274. display commands)
  275. """
  276. wx.EvtHandler.__init__(self)
  277. # Signal when some map is created or updated by a module.
  278. # attributes: name: map name, ltype: map type,
  279. self.mapCreated = Signal('GConsole.mapCreated')
  280. # emitted when map display should be re-render
  281. self.updateMap = Signal('GConsole.updateMap')
  282. # emitted when log message should be written
  283. self.writeLog = Signal('GConsole.writeLog')
  284. # emitted when command log message should be written
  285. self.writeCmdLog = Signal('GConsole.writeCmdLog')
  286. # emitted when warning message should be written
  287. self.writeWarning = Signal('GConsole.writeWarning')
  288. # emitted when error message should be written
  289. self.writeError = Signal('GConsole.writeError')
  290. self._guiparent = guiparent
  291. self._giface = giface
  292. self._ignoredCmdPattern = ignoredCmdPattern
  293. # create queues
  294. self.requestQ = Queue.Queue()
  295. self.resultQ = Queue.Queue()
  296. self.cmdOutputTimer = wx.Timer(self)
  297. self.Bind(wx.EVT_TIMER, self.OnProcessPendingOutputWindowEvents)
  298. self.Bind(EVT_CMD_RUN, self.OnCmdRun)
  299. self.Bind(EVT_CMD_DONE, self.OnCmdDone)
  300. self.Bind(EVT_CMD_ABORT, self.OnCmdAbort)
  301. # stream redirection
  302. self.cmdStdOut = GStdout(receiver=self)
  303. self.cmdStdErr = GStderr(receiver=self)
  304. # thread
  305. self.cmdThread = CmdThread(self, self.requestQ, self.resultQ)
  306. def Redirect(self):
  307. """Redirect stdout/stderr
  308. """
  309. if Debug.GetLevel() == 0 and grass.debug_level(force=True) == 0:
  310. # don't redirect when debugging is enabled
  311. sys.stdout = self.cmdStdOut
  312. sys.stderr = self.cmdStdErr
  313. else:
  314. enc = locale.getdefaultlocale()[1]
  315. if enc:
  316. sys.stdout = codecs.getwriter(enc)(sys.__stdout__)
  317. sys.stderr = codecs.getwriter(enc)(sys.__stderr__)
  318. else:
  319. sys.stdout = sys.__stdout__
  320. sys.stderr = sys.__stderr__
  321. def WriteLog(self, text, style=None, wrap=None,
  322. notification=Notification.HIGHLIGHT):
  323. """Generic method for writing log message in
  324. given style
  325. :param text: text line
  326. :param notification: form of notification
  327. """
  328. self.writeLog.emit(text=text, wrap=wrap,
  329. notification=notification)
  330. def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
  331. """Write message in selected style
  332. :param text: message to be printed
  333. :param pid: process pid or None
  334. :param notification: form of notification
  335. """
  336. self.writeCmdLog.emit(text=text, pid=pid,
  337. notification=notification)
  338. def WriteWarning(self, text):
  339. """Write message in warning style"""
  340. self.writeWarning.emit(text=text)
  341. def WriteError(self, text):
  342. """Write message in error style"""
  343. self.writeError.emit(text=text)
  344. def RunCmd(self, command, compReg=True, skipInterface=False,
  345. onDone=None, onPrepare=None, userData=None, addLayer=None,
  346. notification=Notification.MAKE_VISIBLE):
  347. """Run command typed into console command prompt (GPrompt).
  348. .. todo::
  349. Document the other event.
  350. .. todo::
  351. Solve problem with the other event (now uses gOutputText
  352. event but there is no text, use onPrepare handler instead?)
  353. Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
  354. (according to ignoredCmdPattern) is run.
  355. For example, see layer manager which handles d.* on its own.
  356. :param command: command given as a list (produced e.g. by utils.split())
  357. :param compReg: True use computation region
  358. :param notification: form of notification
  359. :param bool skipInterface: True to do not launch GRASS interface
  360. parser when command has no arguments
  361. given
  362. :param onDone: function to be called when command is finished
  363. :param onPrepare: function to be called before command is launched
  364. :param addLayer: to be passed in the mapCreated signal
  365. :param userData: data defined for the command
  366. """
  367. if len(command) == 0:
  368. Debug.msg(2, "GPrompt:RunCmd(): empty command")
  369. return
  370. # update history file
  371. self.UpdateHistoryFile(' '.join(command))
  372. if command[0] in globalvar.grassCmd:
  373. # send GRASS command without arguments to GUI command interface
  374. # except ignored commands (event is emitted)
  375. if self._ignoredCmdPattern and \
  376. re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
  377. '--help' not in command and '--ui' not in command:
  378. event = gIgnoredCmdRun(cmd=command)
  379. wx.PostEvent(self, event)
  380. return
  381. else:
  382. # other GRASS commands (r|v|g|...)
  383. try:
  384. task = GUI(show=None).ParseCommand(command)
  385. except GException as e:
  386. GError(parent=self._guiparent,
  387. message=unicode(e),
  388. showTraceback=False)
  389. return
  390. hasParams = False
  391. if task:
  392. options = task.get_options()
  393. hasParams = options['params'] and options['flags']
  394. # check for <input>=-
  395. for p in options['params']:
  396. if p.get('prompt', '') == 'input' and \
  397. p.get('element', '') == 'file' and \
  398. p.get('age', 'new') == 'old' and \
  399. p.get('value', '') == '-':
  400. GError(parent=self._guiparent,
  401. message=_("Unable to run command:\n%(cmd)s\n\n"
  402. "Option <%(opt)s>: read from standard input is not "
  403. "supported by wxGUI") % {'cmd': ' '.join(command),
  404. 'opt': p.get('name', '')})
  405. return
  406. # no arguments given
  407. if len(command) == 1 and hasParams and \
  408. not isinstance(self._guiparent, FormNotebook) and \
  409. command[0] != 'v.krige':
  410. # also parent must be checked, see #3135 for details
  411. try:
  412. GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
  413. except GException as e:
  414. print >> sys.stderr, e
  415. return
  416. # activate computational region (set with g.region)
  417. # for all non-display commands.
  418. if compReg:
  419. tmpreg = os.getenv("GRASS_REGION")
  420. if "GRASS_REGION" in os.environ:
  421. del os.environ["GRASS_REGION"]
  422. # process GRASS command with argument
  423. self.cmdThread.RunCmd(command,
  424. stdout=self.cmdStdOut,
  425. stderr=self.cmdStdErr,
  426. onDone=onDone, onPrepare=onPrepare,
  427. userData=userData, addLayer=addLayer,
  428. env=os.environ.copy(),
  429. notification=notification)
  430. self.cmdOutputTimer.Start(50)
  431. # deactivate computational region and return to display settings
  432. if compReg and tmpreg:
  433. os.environ["GRASS_REGION"] = tmpreg
  434. else:
  435. # Send any other command to the shell. Send output to
  436. # console output window
  437. #
  438. # Check if the script has an interface (avoid double-launching
  439. # of the script)
  440. # check if we ignore the command (similar to grass commands part)
  441. if self._ignoredCmdPattern and \
  442. re.compile(self._ignoredCmdPattern).search(' '.join(command)):
  443. event = gIgnoredCmdRun(cmd=command)
  444. wx.PostEvent(self, event)
  445. return
  446. skipInterface = True
  447. if os.path.splitext(command[0])[1] in ('.py', '.sh'):
  448. try:
  449. sfile = open(command[0], "r")
  450. for line in sfile.readlines():
  451. if len(line) < 2:
  452. continue
  453. if line[0] is '#' and line[1] is '%':
  454. skipInterface = False
  455. break
  456. sfile.close()
  457. except IOError:
  458. pass
  459. if len(command) == 1 and not skipInterface:
  460. try:
  461. task = gtask.parse_interface(command[0])
  462. except:
  463. task = None
  464. else:
  465. task = None
  466. if task:
  467. # process GRASS command without argument
  468. GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
  469. else:
  470. self.cmdThread.RunCmd(command,
  471. stdout=self.cmdStdOut,
  472. stderr=self.cmdStdErr,
  473. onDone=onDone, onPrepare=onPrepare,
  474. userData=userData, addLayer=addLayer,
  475. notification=notification)
  476. self.cmdOutputTimer.Start(50)
  477. def GetLog(self, err=False):
  478. """Get widget used for logging
  479. .. todo::
  480. what's this?
  481. :param bool err: True to get stderr widget
  482. """
  483. if err:
  484. return self.cmdStdErr
  485. return self.cmdStdOut
  486. def GetCmd(self):
  487. """Get running command or None"""
  488. return self.requestQ.get()
  489. def OnCmdAbort(self, event):
  490. """Abort running command"""
  491. self.cmdThread.abort()
  492. event.Skip()
  493. def OnCmdRun(self, event):
  494. """Run command"""
  495. self.WriteCmdLog('(%s)\n%s' % (str(time.ctime()), ' '.join(event.cmd)),
  496. notification=event.notification)
  497. event.Skip()
  498. def OnCmdDone(self, event):
  499. """Command done (or aborted)
  500. Sends signal mapCreated if map is recognized in output
  501. parameters or for specific modules (as r.colors).
  502. """
  503. # Process results here
  504. try:
  505. ctime = time.time() - event.time
  506. if ctime < 60:
  507. stime = _("%d sec") % int(ctime)
  508. else:
  509. mtime = int(ctime / 60)
  510. stime = _("%(min)d min %(sec)d sec") % {'min': mtime,
  511. 'sec': int(ctime - (mtime * 60))}
  512. except KeyError:
  513. # stopped deamon
  514. stime = _("unknown")
  515. if event.aborted:
  516. # Thread aborted (using our convention of None return)
  517. self.WriteWarning(_('Please note that the data are left in'
  518. ' inconsistent state and may be corrupted'))
  519. msg = _('Command aborted')
  520. else:
  521. msg = _('Command finished')
  522. self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime),
  523. notification=event.notification)
  524. if event.onDone:
  525. event.onDone(event)
  526. self.cmdOutputTimer.Stop()
  527. if event.cmd[0] == 'g.gisenv':
  528. Debug.SetLevel()
  529. self.Redirect()
  530. # do nothing when no map added
  531. if event.returncode != 0 or event.aborted:
  532. event.Skip()
  533. return
  534. if event.cmd[0] not in globalvar.grassCmd:
  535. return
  536. # find which maps were created
  537. try:
  538. task = GUI(show=None).ParseCommand(event.cmd)
  539. except GException as e:
  540. print >> sys.stderr, e
  541. task = None
  542. return
  543. name = task.get_name()
  544. for p in task.get_options()['params']:
  545. prompt = p.get('prompt', '')
  546. if prompt in ('raster', 'vector', '3d-raster') and p.get('value', None):
  547. if p.get('age', 'old') == 'new' or \
  548. name in ('r.colors', 'r3.colors', 'v.colors', 'v.proj', 'r.proj'):
  549. # if multiple maps (e.g. r.series.interp), we need add each
  550. if p.get('multiple', False):
  551. lnames = p.get('value').split(',')
  552. # in case multiple input (old) maps in r.colors
  553. # we don't want to rerender it multiple times! just once
  554. if p.get('age', 'old') == 'old':
  555. lnames = lnames[0:1]
  556. else:
  557. lnames = [p.get('value')]
  558. for lname in lnames:
  559. if '@' not in lname:
  560. lname += '@' + grass.gisenv()['MAPSET']
  561. if grass.find_file(lname, element=p.get('element'))['fullname']:
  562. self.mapCreated.emit(name=lname, ltype=prompt, add=event.addLayer)
  563. if name == 'r.mask':
  564. self.updateMap.emit()
  565. event.Skip()
  566. def OnProcessPendingOutputWindowEvents(self, event):
  567. wx.GetApp().ProcessPendingEvents()
  568. def UpdateHistoryFile(self, command):
  569. """Update history file
  570. :param command: the command given as a string
  571. """
  572. env = grass.gisenv()
  573. try:
  574. filePath = os.path.join(env['GISDBASE'],
  575. env['LOCATION_NAME'],
  576. env['MAPSET'],
  577. '.bash_history')
  578. fileHistory = codecs.open(filePath, encoding='utf-8', mode='a')
  579. except IOError as e:
  580. GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
  581. {'filePath': filePath, 'error': e},
  582. parent=self._guiparent)
  583. return
  584. try:
  585. fileHistory.write(command + os.linesep)
  586. finally:
  587. fileHistory.close()
  588. # update wxGUI prompt
  589. if self._giface:
  590. self._giface.UpdateCmdHistory(command)