gcmd.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. # create command thread
  270. #
  271. self.cmdThread = CommandThread(cmd, stdin,
  272. stdout, stderr)
  273. self.cmdThread.start()
  274. if wait:
  275. self.cmdThread.join()
  276. if self.cmdThread.module:
  277. self.cmdThread.module.wait()
  278. self.returncode = self.cmdThread.module.returncode
  279. else:
  280. self.returncode = 1
  281. else:
  282. self.cmdThread.join(0.5)
  283. self.returncode = None
  284. if self.returncode is not None:
  285. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" % \
  286. (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
  287. if rerr is not None and self.returncode != 0:
  288. if rerr is False: # GUI dialog
  289. raise CmdError(cmd=self.cmd,
  290. message="%s '%s'%s%s%s %s%s" %
  291. (_("Execution failed:"),
  292. ' '.join(self.cmd),
  293. os.linesep, os.linesep,
  294. _("Details:"),
  295. os.linesep,
  296. _("Error: ") + self.GetError()))
  297. elif rerr == sys.stderr: # redirect message to sys
  298. stderr.write("Execution failed: '%s'" % (' '.join(self.cmd)))
  299. stderr.write("%sDetails:%s%s" % (os.linesep,
  300. _("Error: ") + self.GetError(),
  301. os.linesep))
  302. else:
  303. pass # nop
  304. else:
  305. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" % \
  306. (' '.join(cmd), wait, self.cmdThread.isAlive()))
  307. if verbose_orig:
  308. os.environ["GRASS_VERBOSE"] = verbose_orig
  309. else:
  310. os.unsetenv("GRASS_VERBOSE")
  311. def __ReadOutput(self, stream):
  312. """Read stream and return list of lines
  313. @param stream stream to be read
  314. """
  315. lineList = []
  316. if stream is None:
  317. return lineList
  318. while True:
  319. line = stream.readline()
  320. if not line:
  321. break
  322. line = line.replace('%s' % os.linesep, '').strip()
  323. lineList.append(line)
  324. return lineList
  325. def ReadStdOutput(self):
  326. """Read standard output and return list of lines"""
  327. if self.cmdThread.stdout:
  328. stream = self.cmdThread.stdout # use redirected stream instead
  329. stream.seek(0)
  330. else:
  331. stream = self.cmdThread.module.stdout
  332. return self.__ReadOutput(stream)
  333. def ReadErrOutput(self):
  334. """Read standard error output and return list of lines"""
  335. return self.__ReadOutput(self.cmdThread.module.stderr)
  336. def __ProcessStdErr(self):
  337. """
  338. Read messages/warnings/errors from stderr
  339. @return list of (type, message)
  340. """
  341. if self.stderr is None:
  342. lines = self.ReadErrOutput()
  343. else:
  344. lines = self.cmdThread.error.strip('%s' % os.linesep). \
  345. split('%s' % os.linesep)
  346. msg = []
  347. type = None
  348. content = ""
  349. for line in lines:
  350. if len(line) == 0:
  351. continue
  352. if 'GRASS_' in line: # error or warning
  353. if 'GRASS_INFO_WARNING' in line: # warning
  354. type = "WARNING"
  355. elif 'GRASS_INFO_ERROR' in line: # error
  356. type = "ERROR"
  357. elif 'GRASS_INFO_END': # end of message
  358. msg.append((type, content))
  359. type = None
  360. content = ""
  361. if type:
  362. content += line.split(':')[1].strip()
  363. else: # stderr
  364. msg.append((None, line.strip()))
  365. return msg
  366. def GetError(self):
  367. """Get error message or ''"""
  368. for type, msg in self.__ProcessStdErr():
  369. if type == 'ERROR':
  370. return msg
  371. return ''
  372. def PrintModuleOutput(self, error=True, warning=False, message=False):
  373. """Print module errors, warnings, messages to output
  374. @param error print errors
  375. @param warning print warnings
  376. @param message print messages
  377. @return string
  378. """
  379. msgString = ""
  380. for type, msg in self.__ProcessStdErr():
  381. if type:
  382. if (type == 'ERROR' and error) or \
  383. (type == 'WARNING' and warning) or \
  384. (type == 'MESSAGE' and message):
  385. msgString += " " + type + ": " + msg + "%s" % os.linesep
  386. else:
  387. msgString += " " + msg + "%s" % os.linesep
  388. return msgString
  389. class CommandThread(Thread):
  390. """Create separate thread for command
  391. @param cmd GRASS command (given as list)
  392. @param stdin standard input stream
  393. @param stdout redirect standard output or None
  394. @param stderr redirect standard error output or None
  395. """
  396. def __init__ (self, cmd, stdin=None,
  397. stdout=sys.stdout, stderr=sys.stderr):
  398. Thread.__init__(self)
  399. self.cmd = cmd
  400. self.stdin = stdin
  401. self.stdout = stdout
  402. self.stderr = stderr
  403. self.module = None
  404. self.error = ''
  405. self._want_abort = False
  406. self.aborted = False
  407. self.setDaemon(True)
  408. # set message formatting
  409. self.message_format = os.getenv("GRASS_MESSAGE_FORMAT")
  410. os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  411. def __del__(self):
  412. if self.message_format:
  413. os.environ["GRASS_MESSAGE_FORMAT"] = self.message_format
  414. else:
  415. os.unsetenv("GRASS_MESSAGE_FORMAT")
  416. def run(self):
  417. if len(self.cmd) == 0:
  418. return
  419. self.startTime = time.time()
  420. try:
  421. self.module = Popen(self.cmd,
  422. stdin=subprocess.PIPE,
  423. stdout=subprocess.PIPE,
  424. stderr=subprocess.PIPE)
  425. except OSError, e:
  426. self.error = str(e)
  427. return 1
  428. if self.stdin: # read stdin if requested ...
  429. self.module.stdin.write(self.stdin)
  430. self.module.stdin.close()
  431. # redirect standard outputs...
  432. if self.stdout or self.stderr:
  433. self.__redirect_stream()
  434. def __redirect_stream(self):
  435. """Redirect stream"""
  436. if self.stdout:
  437. # make module stdout/stderr non-blocking
  438. out_fileno = self.module.stdout.fileno()
  439. if not subprocess.mswindows:
  440. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  441. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  442. if self.stderr:
  443. # make module stdout/stderr non-blocking
  444. out_fileno = self.module.stderr.fileno()
  445. if not subprocess.mswindows:
  446. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  447. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  448. # wait for the process to end, sucking in stuff until it does end
  449. while self.module.poll() is None:
  450. if self._want_abort: # abort running process
  451. self.module.kill()
  452. self.aborted = True
  453. return
  454. if self.stdout:
  455. line = recv_some(self.module, e=0, stderr=0)
  456. self.stdout.write(line)
  457. if self.stderr:
  458. line = recv_some(self.module, e=0, stderr=1)
  459. self.stderr.write(line)
  460. if len(line) > 0:
  461. self.error = line
  462. # get the last output
  463. if self.stdout:
  464. line = recv_some(self.module, e=0, stderr=0)
  465. self.stdout.write(line)
  466. if self.stderr:
  467. line = recv_some(self.module, e=0, stderr=1)
  468. self.stderr.write(line)
  469. if len(line) > 0:
  470. self.error = line
  471. def abort(self):
  472. """Abort running process, used by main thread to signal an abort"""
  473. self._want_abort = True