gconsole.py 26 KB

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