gcmd.py 18 KB

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