gcmd.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. """
  2. @package gcmd
  3. @brief GRASS command interface
  4. Classes:
  5. * GException
  6. * DigitError
  7. * Popen (from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554)
  8. * Command
  9. * CommandThread
  10. (C) 2007-2008 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Jachym Cepicky
  15. Martin Landa <landa.martin gmail.com>
  16. @date 2007-2008
  17. """
  18. import os
  19. import sys
  20. import time
  21. import errno
  22. import signal
  23. import wx
  24. try:
  25. import subprocess
  26. except:
  27. compatPath = os.path.join(globalvar.ETCWXDIR, "compat")
  28. sys.path.append(compatPath)
  29. import subprocess
  30. if subprocess.mswindows:
  31. from win32file import ReadFile, WriteFile
  32. from win32pipe import PeekNamedPipe
  33. import msvcrt
  34. else:
  35. import select
  36. import fcntl
  37. from threading import Thread
  38. # import wxgui_utils # log window
  39. import globalvar
  40. import utils
  41. from debug import Debug as Debug
  42. class GException(Exception):
  43. """Generic exception"""
  44. def __init__(self, message, title=_("Error"), parent=None):
  45. self.message = message
  46. self.parent = parent
  47. self.title = title
  48. def __str__(self):
  49. wx.MessageBox(parent=self.parent,
  50. caption=self.title,
  51. message=self.message,
  52. style=wx.ICON_ERROR | wx.CENTRE)
  53. # return 'GException: %s' % self.message
  54. return ''
  55. class GStdError(GException):
  56. """Generic exception"""
  57. def __init__(self, message, title=_("Error"), parent=None):
  58. GException.__init__(self, message, title=title, parent=parent)
  59. class CmdError(GException):
  60. """Exception used for GRASS commands.
  61. See Command class (command exits with EXIT_FAILURE,
  62. G_fatal_error() is called)."""
  63. def __init__(self, cmd, message, parent=None):
  64. self.cmd = cmd
  65. GException.__init__(self, message,
  66. title=_("Error in command execution %s" % self.cmd[0]),
  67. parent=parent)
  68. class SettingsError(GException):
  69. """Exception used for GRASS settings, see
  70. gui_modules/preferences.py."""
  71. def __init__(self, message, parent=None):
  72. GException.__init__(self, message,
  73. title=_("Preferences error"),
  74. parent=parent)
  75. class DigitError(GException):
  76. """Exception raised during digitization session"""
  77. def __init__(self, message, parent=None):
  78. GException.__init__(self, message,
  79. title=_("Error in digitization tool"),
  80. parent=parent)
  81. class DBMError(GException):
  82. """Exception raised for Attribute Table Manager"""
  83. def __init__(self, message, parent=None):
  84. GException.__init__(self, message,
  85. title=_("Error in Attribute Table Manager"),
  86. parent=parent)
  87. class Popen(subprocess.Popen):
  88. """Subclass subprocess.Popen"""
  89. def recv(self, maxsize=None):
  90. return self._recv('stdout', maxsize)
  91. def recv_err(self, maxsize=None):
  92. return self._recv('stderr', maxsize)
  93. def send_recv(self, input='', maxsize=None):
  94. return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
  95. def get_conn_maxsize(self, which, maxsize):
  96. if maxsize is None:
  97. maxsize = 1024
  98. elif maxsize < 1:
  99. maxsize = 1
  100. return getattr(self, which), maxsize
  101. def _close(self, which):
  102. getattr(self, which).close()
  103. setattr(self, which, None)
  104. def kill(self):
  105. """Try to kill running process"""
  106. if subprocess.mswindows:
  107. import win32api
  108. handle = win32api.OpenProcess(1, 0, self.pid)
  109. return (0 != win32api.TerminateProcess(handle, 0))
  110. else:
  111. try:
  112. os.kill(-self.pid, signal.SIGTERM) # kill whole group
  113. except OSError:
  114. pass
  115. if subprocess.mswindows:
  116. def send(self, input):
  117. if not self.stdin:
  118. return None
  119. try:
  120. x = msvcrt.get_osfhandle(self.stdin.fileno())
  121. (errCode, written) = WriteFile(x, input)
  122. except ValueError:
  123. return self._close('stdin')
  124. except (subprocess.pywintypes.error, Exception), why:
  125. if why[0] in (109, errno.ESHUTDOWN):
  126. return self._close('stdin')
  127. raise
  128. return written
  129. def _recv(self, which, maxsize):
  130. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  131. if conn is None:
  132. return None
  133. try:
  134. x = msvcrt.get_osfhandle(conn.fileno())
  135. (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
  136. if maxsize < nAvail:
  137. nAvail = maxsize
  138. if nAvail > 0:
  139. (errCode, read) = ReadFile(x, nAvail, None)
  140. except ValueError:
  141. return self._close(which)
  142. except (subprocess.pywintypes.error, Exception), why:
  143. if why[0] in (109, errno.ESHUTDOWN):
  144. return self._close(which)
  145. raise
  146. if self.universal_newlines:
  147. read = self._translate_newlines(read)
  148. return read
  149. else:
  150. def send(self, input):
  151. if not self.stdin:
  152. return None
  153. if not select.select([], [self.stdin], [], 0)[1]:
  154. return 0
  155. try:
  156. written = os.write(self.stdin.fileno(), input)
  157. except OSError, why:
  158. if why[0] == errno.EPIPE: #broken pipe
  159. return self._close('stdin')
  160. raise
  161. return written
  162. def _recv(self, which, maxsize):
  163. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  164. if conn is None:
  165. return None
  166. flags = fcntl.fcntl(conn, fcntl.F_GETFL)
  167. if not conn.closed:
  168. fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  169. try:
  170. if not select.select([conn], [], [], 0)[0]:
  171. return ''
  172. r = conn.read(maxsize)
  173. if not r:
  174. return self._close(which)
  175. if self.universal_newlines:
  176. r = self._translate_newlines(r)
  177. return r
  178. finally:
  179. if not conn.closed:
  180. fcntl.fcntl(conn, fcntl.F_SETFL, flags)
  181. message = "Other end disconnected!"
  182. def recv_some(p, t=.1, e=1, tr=5, stderr=0):
  183. if tr < 1:
  184. tr = 1
  185. x = time.time()+t
  186. y = []
  187. r = ''
  188. pr = p.recv
  189. if stderr:
  190. pr = p.recv_err
  191. while time.time() < x or r:
  192. r = pr()
  193. if r is None:
  194. if e:
  195. raise Exception(message)
  196. else:
  197. break
  198. elif r:
  199. y.append(r)
  200. else:
  201. time.sleep(max((x-time.time())/tr, 0))
  202. return ''.join(y)
  203. def send_all(p, data):
  204. while len(data):
  205. sent = p.send(data)
  206. if sent is None:
  207. raise Exception(message)
  208. data = buffer(data, sent)
  209. # Define notification event for thread completion
  210. EVT_RESULT_ID = wx.NewId()
  211. def EVT_RESULT(win, func):
  212. """Define Result Event"""
  213. win.Connect(-1, -1, EVT_RESULT_ID, func)
  214. class ResultEvent(wx.PyEvent):
  215. """Simple event to carry arbitrary result data"""
  216. def __init__(self, data):
  217. wx.PyEvent.__init__(self)
  218. self.SetEventType(EVT_RESULT_ID)
  219. self.cmdThread = data
  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. # hack around platform-specific extension for binaries
  249. if self.cmd[0] in globalvar.grassCmd['script']:
  250. self.cmd[0] = self.cmd[0] + globalvar.EXT_SCT
  251. else:
  252. self.cmd[0] = self.cmd[0] + globalvar.EXT_BIN
  253. self.stderr = stderr
  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. #
  279. # start thread
  280. #
  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. self.PrintModuleOutput()))
  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. self.PrintModuleOutput(),
  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 message_format:
  316. os.environ["GRASS_MESSAGE_FORMAT"] = message_format
  317. else:
  318. os.unsetenv("GRASS_MESSAGE_FORMAT")
  319. if verbose_orig:
  320. os.environ["GRASS_VERBOSE"] = verbose_orig
  321. else:
  322. os.unsetenv("GRASS_VERBOSE")
  323. def __ReadOutput(self, stream):
  324. """Read stream and return list of lines
  325. @param stream stream to be read
  326. """
  327. lineList = []
  328. if stream is None:
  329. return lineList
  330. while True:
  331. line = stream.readline()
  332. if not line:
  333. break
  334. line = line.replace('%s' % os.linesep, '').strip()
  335. lineList.append(line)
  336. return lineList
  337. def ReadStdOutput(self):
  338. """Read standard output and return list of lines"""
  339. if self.cmdThread.stdout:
  340. stream = self.cmdThread.stdout # use redirected stream instead
  341. stream.seek(0)
  342. else:
  343. stream = self.cmdThread.module.stdout
  344. return self.__ReadOutput(stream)
  345. def ReadErrOutput(self):
  346. """Read standard error output and return list of lines"""
  347. return self.__ReadOutput(self.cmdThread.module.stderr)
  348. def __ProcessStdErr(self):
  349. """
  350. Read messages/warnings/errors from stderr
  351. @return list of (type, message)
  352. """
  353. if self.stderr is None:
  354. lines = self.ReadErrOutput()
  355. else:
  356. lines = self.cmdThread.rerr.strip('%s' % os.linesep). \
  357. split('%s' % os.linesep)
  358. msg = []
  359. type = None
  360. content = ""
  361. for line in lines:
  362. if len(line) == 0:
  363. continue
  364. if 'GRASS_' in line: # error or warning
  365. if 'GRASS_INFO_WARNING' in line: # warning
  366. type = "WARNING"
  367. elif 'GRASS_INFO_ERROR' in line: # error
  368. type = "ERROR"
  369. elif 'GRASS_INFO_END': # end of message
  370. msg.append((type, content))
  371. type = None
  372. content = ""
  373. if type:
  374. content += line.split(':')[1].strip()
  375. else: # stderr
  376. msg.append((None, line.strip()))
  377. return msg
  378. def PrintModuleOutput(self, error=True, warning=False, message=False):
  379. """Print module errors, warnings, messages to output
  380. @param error print errors
  381. @param warning print warnings
  382. @param message print messages
  383. @return string
  384. """
  385. msgString = ""
  386. for type, msg in self.__ProcessStdErr():
  387. if type:
  388. if (type == 'ERROR' and error) or \
  389. (type == 'WARNING' and warning) or \
  390. (type == 'MESSAGE' and message):
  391. msgString += " " + type + ": " + msg + "%s" % os.linesep
  392. else:
  393. msgString += " " + msg + "%s" % os.linesep
  394. return msgString
  395. class CommandThread(Thread):
  396. """Run command in separate thread
  397. @param cmd GRASS command (given as list)
  398. @param stdin standard input stream
  399. @param stdout redirect standard output or None
  400. @param stderr redirect standard error output or None
  401. """
  402. def __init__ (self, cmd, stdin=None,
  403. stdout=None, stderr=sys.stderr):
  404. Thread.__init__(self)
  405. self.cmd = cmd
  406. self.stdin = stdin
  407. self.stdout = stdout
  408. self.stderr = stderr
  409. self.module = None
  410. self.rerr = ''
  411. self._want_abort = False
  412. self.aborted = False
  413. self.startTime = None
  414. self.setDaemon(True)
  415. def run(self):
  416. """Run command"""
  417. if len(self.cmd) == 0:
  418. return
  419. self.startTime = time.time()
  420. # TODO: wx.Exectute/wx.Process (?)
  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.rerr = str(e)
  428. return
  429. # raise CmdError(self.cmd[0], str(e))
  430. if self.stdin: # read stdin if requested ...
  431. self.module.stdin.write(self.stdin)
  432. self.module.stdin.close()
  433. # redirect standard outputs...
  434. if self.stdout or self.stderr:
  435. self.__redirect_stream()
  436. def __read_all(self, fd):
  437. out = ""
  438. while True:
  439. try:
  440. bytes = fd.read(4096)
  441. except IOError, e:
  442. if e[0] != errno.EAGAIN:
  443. raise
  444. break
  445. if not bytes:
  446. break
  447. out += bytes
  448. return out
  449. def __redirect_stream(self):
  450. """Redirect stream"""
  451. if self.stdout:
  452. # make module stdout/stderr non-blocking
  453. out_fileno = self.module.stdout.fileno()
  454. if not subprocess.mswindows:
  455. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  456. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  457. if self.stderr:
  458. # make module stdout/stderr non-blocking
  459. out_fileno = self.module.stderr.fileno()
  460. if not subprocess.mswindows:
  461. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  462. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  463. # wait for the process to end, sucking in stuff until it does end
  464. while self.module.poll() is None:
  465. time.sleep(.1)
  466. if self._want_abort: # abort running process
  467. self.module.kill()
  468. self.aborted = True
  469. if hasattr(self.stderr, "gmstc"):
  470. # -> GMConsole
  471. wx.PostEvent(self.stderr.gmstc.parent, ResultEvent(self))
  472. return
  473. if self.stdout:
  474. # line = self.__read_all(self.module.stdout)
  475. line = recv_some(self.module, e=0, stderr=0)
  476. self.stdout.write(line)
  477. if self.stderr:
  478. # line = self.__read_all(self.module.stderr)
  479. line = recv_some(self.module, e=0, stderr=1)
  480. self.stderr.write(line)
  481. self.rerr = line
  482. # get the last output
  483. if self.stdout:
  484. # line = self.__read_all(self.module.stdout)
  485. line = recv_some(self.module, e=0, stderr=0)
  486. self.stdout.write(line)
  487. if self.stderr:
  488. # line = self.__read_all(self.module.stderr)
  489. line = recv_some(self.module, e=0, stderr=1)
  490. self.stderr.write(line)
  491. if len(line) > 0:
  492. self.rerr = line
  493. if hasattr(self.stderr, "gmstc"):
  494. # -> GMConsole
  495. wx.PostEvent(self.stderr.gmstc.parent, ResultEvent(self))
  496. def abort(self):
  497. """Abort running process, used by main thread to signal an abort"""
  498. self._want_abort = True
  499. # testing ...
  500. if __name__ == "__main__":
  501. SEP = "-----------------------------------------------------------------------------"
  502. print SEP
  503. # d.rast verbosely, wait for process termination
  504. print "Running d.rast..."
  505. cmd = Command(cmd=["d.rast", "elevation.dem"], verbose=3, wait=True, rerr=True)
  506. if cmd.returncode == None:
  507. print "RUNNING"
  508. elif cmd.returncode == 0:
  509. print "SUCCESS"
  510. else:
  511. print "FAILURE (%d)" % cmd.returncode
  512. print SEP
  513. # v.net.path silently, wait for process termination
  514. print "Running v.net.path for 0 593527.6875 4925297.0625 602083.875 4917545.8125..."
  515. cmd = Command(cmd=["v.net.path", "in=roads@PERMANENT", "out=tmp", "dmax=100000", "--o"],
  516. stdin="0 593527.6875 4925297.0625 602083.875 4917545.8125",
  517. verbose=0,
  518. wait=True, rerr=None)
  519. if cmd.returncode == None:
  520. print "RUNNING"
  521. elif cmd.returncode == 0:
  522. print "SUCCESS"
  523. else:
  524. print "FAILURE (%d)" % cmd.returncode
  525. print SEP
  526. # d.vect silently, do not wait for process termination
  527. # returncode will be None
  528. print "Running d.vect tmp..."
  529. cmd = Command(["d.vect", "tmp"], verbose=2, wait=False, rerr=None)
  530. if cmd.returncode == None:
  531. print "RUNNING"
  532. elif cmd.returncode == 0:
  533. print "SUCCESS"
  534. else:
  535. print "FAILURE (%d)" % cmd.returncode
  536. cmd = Command(["g.region", "-p"])
  537. for line in cmd.ReadStdOutput():
  538. print line
  539. cmd = Command(["g.region", "-p"], stderr=None)
  540. for line in cmd.ReadStdOutput():
  541. print line
  542. for line in cmd.ReadErrOutput():
  543. print line