gcmd.py 17 KB

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