gcmd.py 18 KB

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