gcmd.py 18 KB

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