gcmd.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. class GStdError(GException):
  55. """Generic exception"""
  56. def __init__(self, message, title=_("Error"), parent=None):
  57. GException.__init__(self, message, title=title, parent=parent)
  58. class CmdError(GException):
  59. """Exception used for GRASS commands.
  60. See Command class (command exits with EXIT_FAILURE,
  61. G_fatal_error() is called)."""
  62. def __init__(self, cmd, message, parent=None):
  63. self.cmd = cmd
  64. GException.__init__(self, message,
  65. title=_("Error in command execution %s" % self.cmd[0]),
  66. parent=parent)
  67. class SettingsError(GException):
  68. """Exception used for GRASS settings, see
  69. gui_modules/preferences.py."""
  70. def __init__(self, message, parent=None):
  71. GException.__init__(self, message,
  72. title=_("Preferences error"),
  73. parent=parent)
  74. class DigitError(GException):
  75. """Exception raised during digitization session"""
  76. def __init__(self, message, parent=None):
  77. GException.__init__(self, message,
  78. title=_("Error in digitization tool"),
  79. parent=parent)
  80. class DBMError(GException):
  81. """Exception raised for Attribute Table Manager"""
  82. def __init__(self, message, parent=None):
  83. GException.__init__(self, message,
  84. title=_("Error in Attribute Table Manager"),
  85. parent=parent)
  86. class Popen(subprocess.Popen):
  87. """Subclass subprocess.Popen"""
  88. def recv(self, maxsize=None):
  89. return self._recv('stdout', maxsize)
  90. def recv_err(self, maxsize=None):
  91. return self._recv('stderr', maxsize)
  92. def send_recv(self, input='', maxsize=None):
  93. return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
  94. def get_conn_maxsize(self, which, maxsize):
  95. if maxsize is None:
  96. maxsize = 1024
  97. elif maxsize < 1:
  98. maxsize = 1
  99. return getattr(self, which), maxsize
  100. def _close(self, which):
  101. getattr(self, which).close()
  102. setattr(self, which, None)
  103. def kill(self):
  104. """Try to kill running process"""
  105. if subprocess.mswindows:
  106. import win32api
  107. handle = win32api.OpenProcess(1, 0, self.pid)
  108. return (0 != win32api.TerminateProcess(handle, 0))
  109. else:
  110. try:
  111. os.kill(-self.pid, signal.SIGTERM) # kill whole group
  112. except OSError:
  113. pass
  114. if subprocess.mswindows:
  115. def send(self, input):
  116. if not self.stdin:
  117. return None
  118. try:
  119. x = msvcrt.get_osfhandle(self.stdin.fileno())
  120. (errCode, written) = WriteFile(x, input)
  121. except ValueError:
  122. return self._close('stdin')
  123. except (subprocess.pywintypes.error, Exception), why:
  124. if why[0] in (109, errno.ESHUTDOWN):
  125. return self._close('stdin')
  126. raise
  127. return written
  128. def _recv(self, which, maxsize):
  129. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  130. if conn is None:
  131. return None
  132. try:
  133. x = msvcrt.get_osfhandle(conn.fileno())
  134. (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
  135. if maxsize < nAvail:
  136. nAvail = maxsize
  137. if nAvail > 0:
  138. (errCode, read) = ReadFile(x, nAvail, None)
  139. except ValueError:
  140. return self._close(which)
  141. except (subprocess.pywintypes.error, Exception), why:
  142. if why[0] in (109, errno.ESHUTDOWN):
  143. return self._close(which)
  144. raise
  145. if self.universal_newlines:
  146. read = self._translate_newlines(read)
  147. return read
  148. else:
  149. def send(self, input):
  150. if not self.stdin:
  151. return None
  152. if not select.select([], [self.stdin], [], 0)[1]:
  153. return 0
  154. try:
  155. written = os.write(self.stdin.fileno(), input)
  156. except OSError, why:
  157. if why[0] == errno.EPIPE: #broken pipe
  158. return self._close('stdin')
  159. raise
  160. return written
  161. def _recv(self, which, maxsize):
  162. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  163. if conn is None:
  164. return None
  165. flags = fcntl.fcntl(conn, fcntl.F_GETFL)
  166. if not conn.closed:
  167. fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  168. try:
  169. if not select.select([conn], [], [], 0)[0]:
  170. return ''
  171. r = conn.read(maxsize)
  172. if not r:
  173. return self._close(which)
  174. if self.universal_newlines:
  175. r = self._translate_newlines(r)
  176. return r
  177. finally:
  178. if not conn.closed:
  179. fcntl.fcntl(conn, fcntl.F_SETFL, flags)
  180. message = "Other end disconnected!"
  181. def recv_some(p, t=.1, e=1, tr=5, stderr=0):
  182. if tr < 1:
  183. tr = 1
  184. x = time.time()+t
  185. y = []
  186. r = ''
  187. pr = p.recv
  188. if stderr:
  189. pr = p.recv_err
  190. while time.time() < x or r:
  191. r = pr()
  192. if r is None:
  193. if e:
  194. raise Exception(message)
  195. else:
  196. break
  197. elif r:
  198. y.append(r)
  199. else:
  200. time.sleep(max((x-time.time())/tr, 0))
  201. return ''.join(y)
  202. def send_all(p, data):
  203. while len(data):
  204. sent = p.send(data)
  205. if sent is None:
  206. raise Exception(message)
  207. data = buffer(data, sent)
  208. # Define notification event for thread completion
  209. EVT_RESULT_ID = wx.NewId()
  210. def EVT_RESULT(win, func):
  211. """Define Result Event"""
  212. win.Connect(-1, -1, EVT_RESULT_ID, func)
  213. class ResultEvent(wx.PyEvent):
  214. """Simple event to carry arbitrary result data"""
  215. def __init__(self, data):
  216. wx.PyEvent.__init__(self)
  217. self.SetEventType(EVT_RESULT_ID)
  218. self.cmdThread = data
  219. class Command:
  220. """
  221. Run GRASS command in separate thread
  222. If stdout/err is redirected, write() method is required for the
  223. given classes.
  224. @code
  225. cmd = Command(cmd=['d.rast', 'elevation.dem'], verbose=3, wait=True)
  226. if cmd.returncode == None:
  227. print 'RUNNING?'
  228. elif cmd.returncode == 0:
  229. print 'SUCCESS'
  230. else:
  231. print 'FAILURE (%d)' % cmd.returncode
  232. @endcode
  233. @param cmd command given as list
  234. @param stdin standard input stream
  235. @param verbose verbose level [0, 3] (--q, --v)
  236. @param wait wait for child execution terminated
  237. @param rerr error handling (when CmdError raised).
  238. True for redirection to stderr, False for GUI dialog,
  239. None for no operation (quiet mode)
  240. @param stdout redirect standard output or None
  241. @param stderr redirect standard error output or None
  242. """
  243. def __init__ (self, cmd, stdin=None,
  244. verbose=None, wait=True, rerr=False,
  245. stdout=None, stderr=sys.stderr):
  246. self.cmd = cmd
  247. # hack around platform-specific extension for binaries
  248. if self.cmd[0] in globalvar.grassCmd['script']:
  249. self.cmd[0] = self.cmd[0] + globalvar.EXT_SCT
  250. else:
  251. self.cmd[0] = self.cmd[0] + globalvar.EXT_BIN
  252. self.stderr = stderr
  253. #
  254. # set verbosity level
  255. #
  256. verbose_orig = None
  257. if ('--q' not in self.cmd and '--quiet' not in self.cmd) and \
  258. ('--v' not in self.cmd and '--verbose' not in self.cmd):
  259. if verbose is not None:
  260. if verbose == 0:
  261. self.cmd.append('--quiet')
  262. elif verbose == 3:
  263. self.cmd.append('--verbose')
  264. else:
  265. verbose_orig = os.getenv("GRASS_VERBOSE")
  266. os.environ["GRASS_VERBOSE"] = str(verbose)
  267. #
  268. # set message formatting
  269. #
  270. message_format = os.getenv("GRASS_MESSAGE_FORMAT")
  271. os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  272. #
  273. # create command thread
  274. #
  275. self.cmdThread = CommandThread(cmd, stdin,
  276. stdout, stderr)
  277. #
  278. # start thread
  279. #
  280. self.cmdThread.start()
  281. if wait:
  282. self.cmdThread.join()
  283. self.cmdThread.module.wait()
  284. self.returncode = self.cmdThread.module.returncode
  285. else:
  286. self.cmdThread.join(0.5)
  287. self.returncode = None
  288. if self.returncode is not None:
  289. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" % \
  290. (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
  291. if rerr is not None and self.returncode != 0:
  292. if rerr is False: # GUI dialog
  293. raise CmdError(cmd=self.cmd,
  294. message="%s '%s'%s%s%s %s%s" %
  295. (_("Execution failed:"),
  296. ' '.join(self.cmd),
  297. os.linesep, os.linesep,
  298. _("Details:"),
  299. os.linesep,
  300. self.PrintModuleOutput()))
  301. elif rerr == sys.stderr: # redirect message to sys
  302. stderr.write("Execution failed: '%s'" % (' '.join(self.cmd)))
  303. stderr.write("%sDetails:%s%s" % (os.linesep,
  304. self.PrintModuleOutput(),
  305. os.linesep))
  306. else:
  307. pass # nop
  308. else:
  309. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" % \
  310. (' '.join(cmd), wait, self.cmdThread.isAlive()))
  311. if message_format:
  312. os.environ["GRASS_MESSAGE_FORMAT"] = message_format
  313. else:
  314. os.unsetenv("GRASS_MESSAGE_FORMAT")
  315. if verbose_orig:
  316. os.environ["GRASS_VERBOSE"] = verbose_orig
  317. else:
  318. os.unsetenv("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 ReadStdOutput(self):
  334. """Read standard output and return list of lines"""
  335. if self.cmdThread.stdout:
  336. stream = self.cmdThread.stdout # use redirected stream instead
  337. stream.seek(0)
  338. else:
  339. stream = self.cmdThread.module.stdout
  340. return self.__ReadOutput(stream)
  341. def ReadErrOutput(self):
  342. """Read standard error output and return list of lines"""
  343. return self.__ReadOutput(self.cmdThread.module.stderr)
  344. def __ProcessStdErr(self):
  345. """
  346. Read messages/warnings/errors from stderr
  347. @return list of (type, message)
  348. """
  349. if self.stderr is None:
  350. lines = self.ReadErrOutput()
  351. else:
  352. lines = self.cmdThread.rerr.strip('%s' % os.linesep). \
  353. split('%s' % os.linesep)
  354. msg = []
  355. type = None
  356. content = ""
  357. for line in lines:
  358. if len(line) == 0:
  359. continue
  360. if 'GRASS_' in line: # error or warning
  361. if 'GRASS_INFO_WARNING' in line: # warning
  362. type = "WARNING"
  363. elif 'GRASS_INFO_ERROR' in line: # error
  364. type = "ERROR"
  365. elif 'GRASS_INFO_END': # end of message
  366. msg.append((type, content))
  367. type = None
  368. content = ""
  369. if type:
  370. content += line.split(':')[1].strip()
  371. else: # stderr
  372. msg.append((None, line.strip()))
  373. return msg
  374. def PrintModuleOutput(self, error=True, warning=False, message=False):
  375. """Print module errors, warnings, messages to output
  376. @param error print errors
  377. @param warning print warnings
  378. @param message print messages
  379. @return string
  380. """
  381. msgString = ""
  382. for type, msg in self.__ProcessStdErr():
  383. if type:
  384. if (type == 'ERROR' and error) or \
  385. (type == 'WARNING' and warning) or \
  386. (type == 'MESSAGE' and message):
  387. msgString += " " + type + ": " + msg + "%s" % os.linesep
  388. else:
  389. msgString += " " + msg + "%s" % os.linesep
  390. return msgString
  391. class CommandThread(Thread):
  392. """Run command in separate thread
  393. @param cmd GRASS command (given as list)
  394. @param stdin standard input stream
  395. @param stdout redirect standard output or None
  396. @param stderr redirect standard error output or None
  397. """
  398. def __init__ (self, cmd, stdin=None,
  399. stdout=None, stderr=sys.stderr):
  400. Thread.__init__(self)
  401. self.cmd = cmd
  402. self.stdin = stdin
  403. self.stdout = stdout
  404. self.stderr = stderr
  405. self.module = None
  406. self.rerr = ''
  407. self._want_abort = False
  408. self.aborted = False
  409. self.startTime = None
  410. self.setDaemon(True)
  411. def run(self):
  412. """Run command"""
  413. if len(self.cmd) == 0:
  414. return
  415. self.startTime = time.time()
  416. # TODO: wx.Exectute/wx.Process (?)
  417. try:
  418. self.module = Popen(self.cmd,
  419. stdin=subprocess.PIPE,
  420. stdout=subprocess.PIPE,
  421. stderr=subprocess.PIPE)
  422. except OSError, e:
  423. raise CmdError(self.cmd[0], str(e))
  424. if self.stdin: # read stdin if requested ...
  425. self.module.stdin.write(self.stdin)
  426. self.module.stdin.close()
  427. # redirect standard outputs...
  428. if self.stdout or self.stderr:
  429. self.__redirect_stream()
  430. def __read_all(self, fd):
  431. out = ""
  432. while True:
  433. try:
  434. bytes = fd.read(4096)
  435. except IOError, e:
  436. if e[0] != errno.EAGAIN:
  437. raise
  438. break
  439. if not bytes:
  440. break
  441. out += bytes
  442. return out
  443. def __redirect_stream(self):
  444. """Redirect stream"""
  445. if self.stdout:
  446. # make module stdout/stderr non-blocking
  447. out_fileno = self.module.stdout.fileno()
  448. # FIXME (MS Windows)
  449. if not subprocess.mswindows:
  450. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  451. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  452. if self.stderr:
  453. # make module stdout/stderr non-blocking
  454. out_fileno = self.module.stderr.fileno()
  455. # FIXME (MS Windows)
  456. if not subprocess.mswindows:
  457. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  458. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  459. # wait for the process to end, sucking in stuff until it does end
  460. while self.module.poll() is None:
  461. time.sleep(.1)
  462. if self._want_abort: # abort running process
  463. self.module.kill()
  464. self.aborted = True
  465. if hasattr(self.stderr, "gmstc"):
  466. # -> GMConsole
  467. wx.PostEvent(self.stderr.gmstc.parent, ResultEvent(self))
  468. return
  469. if self.stdout:
  470. # line = self.__read_all(self.module.stdout)
  471. line = recv_some(self.module, e=0, stderr=0)
  472. self.stdout.write(line)
  473. if self.stderr:
  474. # line = self.__read_all(self.module.stderr)
  475. line = recv_some(self.module, e=0, stderr=1)
  476. self.stderr.write(line)
  477. self.rerr = line
  478. # get the last output
  479. if self.stdout:
  480. # line = self.__read_all(self.module.stdout)
  481. line = recv_some(self.module, e=0, stderr=0)
  482. self.stdout.write(line)
  483. if self.stderr:
  484. # line = self.__read_all(self.module.stderr)
  485. line = recv_some(self.module, e=0, stderr=1)
  486. self.stderr.write(line)
  487. if len(line) > 0:
  488. self.rerr = line
  489. if hasattr(self.stderr, "gmstc"):
  490. # -> GMConsole
  491. wx.PostEvent(self.stderr.gmstc.parent, ResultEvent(self))
  492. def abort(self):
  493. """Abort running process, used by main thread to signal an abort"""
  494. self._want_abort = True
  495. # testing ...
  496. if __name__ == "__main__":
  497. SEP = "-----------------------------------------------------------------------------"
  498. print SEP
  499. # d.rast verbosely, wait for process termination
  500. print "Running d.rast..."
  501. cmd = Command(cmd=["d.rast", "elevation.dem"], verbose=3, wait=True, rerr=True)
  502. if cmd.returncode == None:
  503. print "RUNNING"
  504. elif cmd.returncode == 0:
  505. print "SUCCESS"
  506. else:
  507. print "FAILURE (%d)" % cmd.returncode
  508. print SEP
  509. # v.net.path silently, wait for process termination
  510. print "Running v.net.path for 0 593527.6875 4925297.0625 602083.875 4917545.8125..."
  511. cmd = Command(cmd=["v.net.path", "in=roads@PERMANENT", "out=tmp", "dmax=100000", "--o"],
  512. stdin="0 593527.6875 4925297.0625 602083.875 4917545.8125",
  513. verbose=0,
  514. wait=True, rerr=None)
  515. if cmd.returncode == None:
  516. print "RUNNING"
  517. elif cmd.returncode == 0:
  518. print "SUCCESS"
  519. else:
  520. print "FAILURE (%d)" % cmd.returncode
  521. print SEP
  522. # d.vect silently, do not wait for process termination
  523. # returncode will be None
  524. print "Running d.vect tmp..."
  525. cmd = Command(["d.vect", "tmp"], verbose=2, wait=False, rerr=None)
  526. if cmd.returncode == None:
  527. print "RUNNING"
  528. elif cmd.returncode == 0:
  529. print "SUCCESS"
  530. else:
  531. print "FAILURE (%d)" % cmd.returncode
  532. cmd = Command(["g.region", "-p"])
  533. for line in cmd.ReadStdOutput():
  534. print line
  535. cmd = Command(["g.region", "-p"], stderr=None)
  536. for line in cmd.ReadStdOutput():
  537. print line
  538. for line in cmd.ReadErrOutput():
  539. print line