gcmd.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. """!
  2. @package gcmd
  3. @brief wxGUI command interface
  4. Classes:
  5. - GException
  6. - GStdError
  7. - CmdError
  8. - SettingsError
  9. - DigitError
  10. - DBMError
  11. - NvizError
  12. - Popen (from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554)
  13. - Command
  14. - CommandThread
  15. Functions:
  16. - RunCommand
  17. (C) 2007-2008, 2010 by the GRASS Development Team
  18. This program is free software under the GNU General Public
  19. License (>=v2). Read the file COPYING that comes with GRASS
  20. for details.
  21. @author Jachym Cepicky
  22. @author Martin Landa <landa.martin gmail.com>
  23. """
  24. import os
  25. import sys
  26. import time
  27. import errno
  28. import signal
  29. import locale
  30. import traceback
  31. import wx
  32. try:
  33. import subprocess
  34. except:
  35. compatPath = os.path.join(globalvar.ETCWXDIR, "compat")
  36. sys.path.append(compatPath)
  37. import subprocess
  38. if subprocess.mswindows:
  39. from win32file import ReadFile, WriteFile
  40. from win32pipe import PeekNamedPipe
  41. import msvcrt
  42. else:
  43. import select
  44. import fcntl
  45. from threading import Thread
  46. import globalvar
  47. grassPath = os.path.join(globalvar.ETCDIR, "python")
  48. sys.path.append(grassPath)
  49. from grass.script import core as grass
  50. import utils
  51. from debug import Debug as Debug
  52. class GMessage:
  53. def __init__(self, parent, message, msgType = 'error'):
  54. if msgType == 'error':
  55. caption = _('Error')
  56. style = wx.OK | wx.ICON_ERROR | wx.CENTRE
  57. exception = traceback.format_exc()
  58. reason = exception.split('\n')[-2].split(':', 1)[-1].strip()
  59. if Debug.get_level() > 0:
  60. sys.stderr.write(exception)
  61. wx.MessageBox(parent = parent,
  62. message = message + '\n\n%s: %s\n\n%s' % \
  63. (_('Reason'),
  64. reason, exception),
  65. caption = caption,
  66. style = style)
  67. class GException(Exception):
  68. """!Generic exception"""
  69. def __init__(self, message, title=_("Error"), parent=None):
  70. self.msg = message
  71. self.parent = parent
  72. self.title = title
  73. def Show(self):
  74. dlg = wx.MessageDialog(parent=self.parent,
  75. caption=self.title,
  76. message=self.msg,
  77. style=wx.ICON_ERROR | wx.CENTRE)
  78. dlg.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass_error.ico'), wx.BITMAP_TYPE_ICO))
  79. if self.parent:
  80. dlg.CentreOnParent()
  81. else:
  82. dlg.CentreOnScreen()
  83. dlg.ShowModal()
  84. def __str__(self):
  85. self.Show()
  86. return ''
  87. class GStdError(GException):
  88. """!Generic exception"""
  89. def __init__(self, message, title=_("Error"), parent=None):
  90. GException.__init__(self, message, title=title, parent=parent)
  91. class CmdError(GException):
  92. """!Exception used for GRASS commands.
  93. See Command class (command exits with EXIT_FAILURE,
  94. G_fatal_error() is called)."""
  95. def __init__(self, cmd, message, parent=None):
  96. GException.__init__(self, message,
  97. title=_("Error in command execution '%s'" % cmd),
  98. parent=parent)
  99. class SettingsError(GException):
  100. """!Exception used for GRASS settings, see
  101. gui_modules/preferences.py."""
  102. def __init__(self, message, parent=None):
  103. GException.__init__(self, message,
  104. title=_("Preferences error"),
  105. parent=parent)
  106. class DigitError(GException):
  107. """!Exception raised during digitization session"""
  108. def __init__(self, message, parent=None):
  109. GException.__init__(self, message,
  110. title=_("Vector digitizer error"),
  111. parent=parent)
  112. class DBMError(GException):
  113. """!Attribute Table Manager exception class"""
  114. def __init__(self, message, parent=None):
  115. GException.__init__(self, message,
  116. title=_("Attribute table manager error"),
  117. parent=parent)
  118. class NvizError(GException):
  119. """!Nviz exception class"""
  120. def __init__(self, message, parent=None):
  121. GException.__init__(self, message,
  122. title=_("Nviz error"),
  123. parent=parent)
  124. class Popen(subprocess.Popen):
  125. """!Subclass subprocess.Popen"""
  126. def __init__(self, *args, **kwargs):
  127. if subprocess.mswindows:
  128. try:
  129. kwargs['args'] = map(utils.EncodeString, kwargs['args'])
  130. except KeyError:
  131. if len(args) > 0:
  132. targs = list(args)
  133. targs[0] = map(utils.EncodeString, args[0])
  134. args = tuple(targs)
  135. subprocess.Popen.__init__(self, *args, **kwargs)
  136. def recv(self, maxsize=None):
  137. return self._recv('stdout', maxsize)
  138. def recv_err(self, maxsize=None):
  139. return self._recv('stderr', maxsize)
  140. def send_recv(self, input='', maxsize=None):
  141. return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
  142. def get_conn_maxsize(self, which, maxsize):
  143. if maxsize is None:
  144. maxsize = 1024
  145. elif maxsize < 1:
  146. maxsize = 1
  147. return getattr(self, which), maxsize
  148. def _close(self, which):
  149. getattr(self, which).close()
  150. setattr(self, which, None)
  151. def kill(self):
  152. """!Try to kill running process"""
  153. if subprocess.mswindows:
  154. import win32api
  155. handle = win32api.OpenProcess(1, 0, self.pid)
  156. return (0 != win32api.TerminateProcess(handle, 0))
  157. else:
  158. try:
  159. os.kill(-self.pid, signal.SIGTERM) # kill whole group
  160. except OSError:
  161. pass
  162. if subprocess.mswindows:
  163. def send(self, input):
  164. if not self.stdin:
  165. return None
  166. try:
  167. x = msvcrt.get_osfhandle(self.stdin.fileno())
  168. (errCode, written) = WriteFile(x, input)
  169. except ValueError:
  170. return self._close('stdin')
  171. except (subprocess.pywintypes.error, Exception), why:
  172. if why[0] in (109, errno.ESHUTDOWN):
  173. return self._close('stdin')
  174. raise
  175. return written
  176. def _recv(self, which, maxsize):
  177. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  178. if conn is None:
  179. return None
  180. try:
  181. x = msvcrt.get_osfhandle(conn.fileno())
  182. (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
  183. if maxsize < nAvail:
  184. nAvail = maxsize
  185. if nAvail > 0:
  186. (errCode, read) = ReadFile(x, nAvail, None)
  187. except ValueError:
  188. return self._close(which)
  189. except (subprocess.pywintypes.error, Exception), why:
  190. if why[0] in (109, errno.ESHUTDOWN):
  191. return self._close(which)
  192. raise
  193. if self.universal_newlines:
  194. read = self._translate_newlines(read)
  195. return read
  196. else:
  197. def send(self, input):
  198. if not self.stdin:
  199. return None
  200. if not select.select([], [self.stdin], [], 0)[1]:
  201. return 0
  202. try:
  203. written = os.write(self.stdin.fileno(), input)
  204. except OSError, why:
  205. if why[0] == errno.EPIPE: #broken pipe
  206. return self._close('stdin')
  207. raise
  208. return written
  209. def _recv(self, which, maxsize):
  210. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  211. if conn is None:
  212. return None
  213. flags = fcntl.fcntl(conn, fcntl.F_GETFL)
  214. if not conn.closed:
  215. fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  216. try:
  217. if not select.select([conn], [], [], 0)[0]:
  218. return ''
  219. r = conn.read(maxsize)
  220. if not r:
  221. return self._close(which)
  222. if self.universal_newlines:
  223. r = self._translate_newlines(r)
  224. return r
  225. finally:
  226. if not conn.closed:
  227. fcntl.fcntl(conn, fcntl.F_SETFL, flags)
  228. message = "Other end disconnected!"
  229. def recv_some(p, t=.1, e=1, tr=5, stderr=0):
  230. if tr < 1:
  231. tr = 1
  232. x = time.time()+t
  233. y = []
  234. r = ''
  235. pr = p.recv
  236. if stderr:
  237. pr = p.recv_err
  238. while time.time() < x or r:
  239. r = pr()
  240. if r is None:
  241. if e:
  242. raise Exception(message)
  243. else:
  244. break
  245. elif r:
  246. y.append(r)
  247. else:
  248. time.sleep(max((x-time.time())/tr, 0))
  249. return ''.join(y)
  250. def send_all(p, data):
  251. while len(data):
  252. sent = p.send(data)
  253. if sent is None:
  254. raise Exception(message)
  255. data = buffer(data, sent)
  256. class Command:
  257. """!Run command in separate thread. Used for commands launched
  258. on the background.
  259. If stdout/err is redirected, write() method is required for the
  260. given classes.
  261. @code
  262. cmd = Command(cmd=['d.rast', 'elevation.dem'], verbose=3, wait=True)
  263. if cmd.returncode == None:
  264. print 'RUNNING?'
  265. elif cmd.returncode == 0:
  266. print 'SUCCESS'
  267. else:
  268. print 'FAILURE (%d)' % cmd.returncode
  269. @endcode
  270. """
  271. def __init__ (self, cmd, stdin=None,
  272. verbose=None, wait=True, rerr=False,
  273. stdout=None, stderr=None):
  274. """
  275. @param cmd command given as list
  276. @param stdin standard input stream
  277. @param verbose verbose level [0, 3] (--q, --v)
  278. @param wait wait for child execution terminated
  279. @param rerr error handling (when CmdError raised).
  280. True for redirection to stderr, False for GUI dialog,
  281. None for no operation (quiet mode)
  282. @param stdout redirect standard output or None
  283. @param stderr redirect standard error output or None
  284. """
  285. self.cmd = cmd
  286. self.stderr = stderr
  287. #
  288. # set verbosity level
  289. #
  290. verbose_orig = None
  291. if ('--q' not in self.cmd and '--quiet' not in self.cmd) and \
  292. ('--v' not in self.cmd and '--verbose' not in self.cmd):
  293. if verbose is not None:
  294. if verbose == 0:
  295. self.cmd.append('--quiet')
  296. elif verbose == 3:
  297. self.cmd.append('--verbose')
  298. else:
  299. verbose_orig = os.getenv("GRASS_VERBOSE")
  300. os.environ["GRASS_VERBOSE"] = str(verbose)
  301. #
  302. # create command thread
  303. #
  304. self.cmdThread = CommandThread(cmd, stdin,
  305. stdout, stderr)
  306. self.cmdThread.start()
  307. if wait:
  308. self.cmdThread.join()
  309. if self.cmdThread.module:
  310. self.cmdThread.module.wait()
  311. self.returncode = self.cmdThread.module.returncode
  312. else:
  313. self.returncode = 1
  314. else:
  315. self.cmdThread.join(0.5)
  316. self.returncode = None
  317. if self.returncode is not None:
  318. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" % \
  319. (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
  320. if rerr is not None and self.returncode != 0:
  321. if rerr is False: # GUI dialog
  322. raise CmdError(cmd=self.cmd,
  323. message="%s '%s'%s%s%s %s%s" %
  324. (_("Execution failed:"),
  325. ' '.join(self.cmd),
  326. os.linesep, os.linesep,
  327. _("Details:"),
  328. os.linesep,
  329. _("Error: ") + self.__GetError()))
  330. elif rerr == sys.stderr: # redirect message to sys
  331. stderr.write("Execution failed: '%s'" % (' '.join(self.cmd)))
  332. stderr.write("%sDetails:%s%s" % (os.linesep,
  333. _("Error: ") + self.__GetError(),
  334. os.linesep))
  335. else:
  336. pass # nop
  337. else:
  338. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" % \
  339. (' '.join(cmd), wait, self.cmdThread.isAlive()))
  340. if verbose_orig:
  341. os.environ["GRASS_VERBOSE"] = verbose_orig
  342. elif os.environ.has_key("GRASS_VERBOSE"):
  343. del os.environ["GRASS_VERBOSE"]
  344. def __ReadOutput(self, stream):
  345. """!Read stream and return list of lines
  346. @param stream stream to be read
  347. """
  348. lineList = []
  349. if stream is None:
  350. return lineList
  351. while True:
  352. line = stream.readline()
  353. if not line:
  354. break
  355. line = line.replace('%s' % os.linesep, '').strip()
  356. lineList.append(line)
  357. return lineList
  358. def __ReadErrOutput(self):
  359. """!Read standard error output and return list of lines"""
  360. return self.__ReadOutput(self.cmdThread.module.stderr)
  361. def __ProcessStdErr(self):
  362. """
  363. Read messages/warnings/errors from stderr
  364. @return list of (type, message)
  365. """
  366. if self.stderr is None:
  367. lines = self.__ReadErrOutput()
  368. else:
  369. lines = self.cmdThread.error.strip('%s' % os.linesep). \
  370. split('%s' % os.linesep)
  371. msg = []
  372. type = None
  373. content = ""
  374. for line in lines:
  375. if len(line) == 0:
  376. continue
  377. if 'GRASS_' in line: # error or warning
  378. if 'GRASS_INFO_WARNING' in line: # warning
  379. type = "WARNING"
  380. elif 'GRASS_INFO_ERROR' in line: # error
  381. type = "ERROR"
  382. elif 'GRASS_INFO_END': # end of message
  383. msg.append((type, content))
  384. type = None
  385. content = ""
  386. if type:
  387. content += line.split(':', 1)[1].strip()
  388. else: # stderr
  389. msg.append((None, line.strip()))
  390. return msg
  391. def __GetError(self):
  392. """!Get error message or ''"""
  393. if not self.cmdThread.module:
  394. return _("Unable to exectute command: '%s'") % ' '.join(self.cmd)
  395. for type, msg in self.__ProcessStdErr():
  396. if type == 'ERROR':
  397. enc = locale.getdefaultlocale()[1]
  398. if enc:
  399. return unicode(msg, enc)
  400. else:
  401. return msg
  402. return ''
  403. class CommandThread(Thread):
  404. """!Create separate thread for command. Used for commands launched
  405. on the background."""
  406. def __init__ (self, cmd, stdin=None,
  407. stdout=sys.stdout, stderr=sys.stderr):
  408. """
  409. @param cmd command (given as list)
  410. @param stdin standard input stream
  411. @param stdout redirect standard output or None
  412. @param stderr redirect standard error output or None
  413. """
  414. Thread.__init__(self)
  415. self.cmd = cmd
  416. self.stdin = stdin
  417. self.stdout = stdout
  418. self.stderr = stderr
  419. self.module = None
  420. self.error = ''
  421. self._want_abort = False
  422. self.aborted = False
  423. self.setDaemon(True)
  424. # set message formatting
  425. self.message_format = os.getenv("GRASS_MESSAGE_FORMAT")
  426. os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  427. def __del__(self):
  428. if self.message_format:
  429. os.environ["GRASS_MESSAGE_FORMAT"] = self.message_format
  430. else:
  431. del os.environ["GRASS_MESSAGE_FORMAT"]
  432. def run(self):
  433. """!Run command"""
  434. if len(self.cmd) == 0:
  435. return
  436. self.startTime = time.time()
  437. try:
  438. self.module = Popen(self.cmd,
  439. stdin=subprocess.PIPE,
  440. stdout=subprocess.PIPE,
  441. stderr=subprocess.PIPE,
  442. shell=sys.platform=="win32")
  443. except OSError, e:
  444. self.error = str(e)
  445. return 1
  446. if self.stdin: # read stdin if requested ...
  447. self.module.stdin.write(self.stdin)
  448. self.module.stdin.close()
  449. # redirect standard outputs...
  450. if self.stdout or self.stderr:
  451. self.__redirect_stream()
  452. def __redirect_stream(self):
  453. """!Redirect stream"""
  454. if self.stdout:
  455. # make module stdout/stderr non-blocking
  456. out_fileno = self.module.stdout.fileno()
  457. if not subprocess.mswindows:
  458. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  459. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  460. if self.stderr:
  461. # make module stdout/stderr non-blocking
  462. out_fileno = self.module.stderr.fileno()
  463. if not subprocess.mswindows:
  464. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  465. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  466. # wait for the process to end, sucking in stuff until it does end
  467. while self.module.poll() is None:
  468. if self._want_abort: # abort running process
  469. self.module.kill()
  470. self.aborted = True
  471. return
  472. if self.stdout:
  473. line = recv_some(self.module, e=0, stderr=0)
  474. self.stdout.write(line)
  475. if self.stderr:
  476. line = recv_some(self.module, e=0, stderr=1)
  477. self.stderr.write(line)
  478. if len(line) > 0:
  479. self.error = line
  480. # get the last output
  481. if self.stdout:
  482. line = recv_some(self.module, e=0, stderr=0)
  483. self.stdout.write(line)
  484. if self.stderr:
  485. line = recv_some(self.module, e=0, stderr=1)
  486. self.stderr.write(line)
  487. if len(line) > 0:
  488. self.error = line
  489. def abort(self):
  490. """!Abort running process, used by main thread to signal an abort"""
  491. self._want_abort = True
  492. def RunCommand(prog, flags = "", overwrite = False, quiet = False, verbose = False,
  493. parent = None, read = False, stdin = None, getErrorMsg = False, **kwargs):
  494. """!Run GRASS command"""
  495. kwargs['stderr'] = subprocess.PIPE
  496. if read:
  497. kwargs['stdout'] = subprocess.PIPE
  498. if stdin:
  499. kwargs['stdin'] = subprocess.PIPE
  500. ps = grass.start_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  501. if stdin:
  502. ps.stdin.write(stdin)
  503. ps.stdin.close()
  504. ps.stdin = None
  505. stdout, stderr = ps.communicate()
  506. ret = ps.returncode
  507. if ret != 0 and parent:
  508. e = CmdError(cmd = prog,
  509. message = stderr,
  510. parent = parent)
  511. e.Show()
  512. if not read:
  513. if not getErrorMsg:
  514. return ret
  515. else:
  516. return ret, stderr
  517. if not getErrorMsg:
  518. return stdout
  519. if read and getErrorMsg:
  520. return ret, stdout, stderr
  521. return stdout, stderr