gcmd.py 20 KB

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