gcmd.py 18 KB

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