gcmd.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. """!
  2. @package core.gcmd
  3. @brief wxGUI command interface
  4. Classes:
  5. - gcmd::GError
  6. - gcmd::GWarning
  7. - gcmd::GMessage
  8. - gcmd::GException
  9. - gcmd::Popen (from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554)
  10. - gcmd::Command
  11. - gcmd::CommandThread
  12. Functions:
  13. - RunCommand
  14. (C) 2007-2008, 2010-2011 by the GRASS Development Team
  15. This program is free software under the GNU General Public License
  16. (>=v2). Read the file COPYING that comes with GRASS for details.
  17. @author Jachym Cepicky
  18. @author Martin Landa <landa.martin gmail.com>
  19. """
  20. import os
  21. import sys
  22. import time
  23. import errno
  24. import signal
  25. import locale
  26. import traceback
  27. import subprocess
  28. if subprocess.mswindows:
  29. from win32file import ReadFile, WriteFile
  30. from win32pipe import PeekNamedPipe
  31. import msvcrt
  32. else:
  33. import select
  34. import fcntl
  35. from threading import Thread
  36. import wx
  37. from grass.script import core as grass
  38. from core import globalvar
  39. from core.debug import Debug
  40. from core.utils import GetRealCmd
  41. def DecodeString(string):
  42. """!Decode string using system encoding
  43. @param string string to be decoded
  44. @return decoded string
  45. """
  46. if not string:
  47. return string
  48. enc = locale.getdefaultlocale()[1]
  49. if enc:
  50. Debug.msg(5, "DecodeString(): enc=%s" % enc)
  51. return string.decode(enc)
  52. return string
  53. def EncodeString(string):
  54. """!Return encoded string using system locales
  55. @param string string to be encoded
  56. @return encoded string
  57. """
  58. if not string:
  59. return string
  60. enc = locale.getdefaultlocale()[1]
  61. if enc:
  62. Debug.msg(5, "EncodeString(): enc=%s" % enc)
  63. return string.encode(enc)
  64. return string
  65. class GError:
  66. def __init__(self, message, parent = None, caption = None, showTraceback = True):
  67. if not caption:
  68. caption = _('Error')
  69. style = wx.OK | wx.ICON_ERROR | wx.CENTRE
  70. exc_type, exc_value, exc_traceback = sys.exc_info()
  71. if exc_traceback:
  72. exception = traceback.format_exc()
  73. reason = exception.splitlines()[-1].split(':', 1)[-1].strip()
  74. if Debug.GetLevel() > 0 and exc_traceback:
  75. sys.stderr.write(exception)
  76. if showTraceback and exc_traceback:
  77. wx.MessageBox(parent = parent,
  78. message = message + '\n\n%s: %s\n\n%s' % \
  79. (_('Reason'),
  80. reason, exception),
  81. caption = caption,
  82. style = style)
  83. else:
  84. wx.MessageBox(parent = parent,
  85. message = message,
  86. caption = caption,
  87. style = style)
  88. class GWarning:
  89. def __init__(self, message, parent = None):
  90. caption = _('Warning')
  91. style = wx.OK | wx.ICON_WARNING | wx.CENTRE
  92. wx.MessageBox(parent = parent,
  93. message = message,
  94. caption = caption,
  95. style = style)
  96. class GMessage:
  97. def __init__(self, message, parent = None):
  98. caption = _('Message')
  99. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE
  100. wx.MessageBox(parent = parent,
  101. message = message,
  102. caption = caption,
  103. style = style)
  104. class GException(Exception):
  105. def __init__(self, value = ''):
  106. self.value = value
  107. def __str__(self):
  108. return str(self.value)
  109. class Popen(subprocess.Popen):
  110. """!Subclass subprocess.Popen"""
  111. def __init__(self, args, **kwargs):
  112. if subprocess.mswindows:
  113. args = map(EncodeString, args)
  114. subprocess.Popen.__init__(self, args, **kwargs)
  115. def recv(self, maxsize = None):
  116. return self._recv('stdout', maxsize)
  117. def recv_err(self, maxsize = None):
  118. return self._recv('stderr', maxsize)
  119. def send_recv(self, input = '', maxsize = None):
  120. return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
  121. def get_conn_maxsize(self, which, maxsize):
  122. if maxsize is None:
  123. maxsize = 1024
  124. elif maxsize < 1:
  125. maxsize = 1
  126. return getattr(self, which), maxsize
  127. def _close(self, which):
  128. getattr(self, which).close()
  129. setattr(self, which, None)
  130. def kill(self):
  131. """!Try to kill running process"""
  132. if subprocess.mswindows:
  133. import win32api
  134. handle = win32api.OpenProcess(1, 0, self.pid)
  135. return (0 != win32api.TerminateProcess(handle, 0))
  136. else:
  137. try:
  138. os.kill(-self.pid, signal.SIGTERM) # kill whole group
  139. except OSError:
  140. pass
  141. if subprocess.mswindows:
  142. def send(self, input):
  143. if not self.stdin:
  144. return None
  145. try:
  146. x = msvcrt.get_osfhandle(self.stdin.fileno())
  147. (errCode, written) = WriteFile(x, input)
  148. except ValueError:
  149. return self._close('stdin')
  150. except (subprocess.pywintypes.error, Exception), why:
  151. if why[0] in (109, errno.ESHUTDOWN):
  152. return self._close('stdin')
  153. raise
  154. return written
  155. def _recv(self, which, maxsize):
  156. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  157. if conn is None:
  158. return None
  159. try:
  160. x = msvcrt.get_osfhandle(conn.fileno())
  161. (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
  162. if maxsize < nAvail:
  163. nAvail = maxsize
  164. if nAvail > 0:
  165. (errCode, read) = ReadFile(x, nAvail, None)
  166. except ValueError:
  167. return self._close(which)
  168. except (subprocess.pywintypes.error, Exception), why:
  169. if why[0] in (109, errno.ESHUTDOWN):
  170. return self._close(which)
  171. raise
  172. if self.universal_newlines:
  173. read = self._translate_newlines(read)
  174. return read
  175. else:
  176. def send(self, input):
  177. if not self.stdin:
  178. return None
  179. if not select.select([], [self.stdin], [], 0)[1]:
  180. return 0
  181. try:
  182. written = os.write(self.stdin.fileno(), input)
  183. except OSError, why:
  184. if why[0] == errno.EPIPE: #broken pipe
  185. return self._close('stdin')
  186. raise
  187. return written
  188. def _recv(self, which, maxsize):
  189. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  190. if conn is None:
  191. return None
  192. flags = fcntl.fcntl(conn, fcntl.F_GETFL)
  193. if not conn.closed:
  194. fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  195. try:
  196. if not select.select([conn], [], [], 0)[0]:
  197. return ''
  198. r = conn.read(maxsize)
  199. if not r:
  200. return self._close(which)
  201. if self.universal_newlines:
  202. r = self._translate_newlines(r)
  203. return r
  204. finally:
  205. if not conn.closed:
  206. fcntl.fcntl(conn, fcntl.F_SETFL, flags)
  207. message = "Other end disconnected!"
  208. def recv_some(p, t = .1, e = 1, tr = 5, stderr = 0):
  209. if tr < 1:
  210. tr = 1
  211. x = time.time()+t
  212. y = []
  213. r = ''
  214. pr = p.recv
  215. if stderr:
  216. pr = p.recv_err
  217. while time.time() < x or r:
  218. r = pr()
  219. if r is None:
  220. if e:
  221. raise Exception(message)
  222. else:
  223. break
  224. elif r:
  225. y.append(r)
  226. else:
  227. time.sleep(max((x-time.time())/tr, 0))
  228. return ''.join(y)
  229. def send_all(p, data):
  230. while len(data):
  231. sent = p.send(data)
  232. if sent is None:
  233. raise Exception(message)
  234. data = buffer(data, sent)
  235. class Command:
  236. """!Run command in separate thread. Used for commands launched
  237. on the background.
  238. If stdout/err is redirected, write() method is required for the
  239. given classes.
  240. @code
  241. cmd = Command(cmd=['d.rast', 'elevation.dem'], verbose=3, wait=True)
  242. if cmd.returncode == None:
  243. print 'RUNNING?'
  244. elif cmd.returncode == 0:
  245. print 'SUCCESS'
  246. else:
  247. print 'FAILURE (%d)' % cmd.returncode
  248. @endcode
  249. """
  250. def __init__ (self, cmd, stdin = None,
  251. verbose = None, wait = True, rerr = False,
  252. stdout = None, stderr = None):
  253. """
  254. @param cmd command given as list
  255. @param stdin standard input stream
  256. @param verbose verbose level [0, 3] (--q, --v)
  257. @param wait wait for child execution terminated
  258. @param rerr error handling (when GException raised).
  259. True for redirection to stderr, False for GUI dialog,
  260. None for no operation (quiet mode)
  261. @param stdout redirect standard output or None
  262. @param stderr redirect standard error output or None
  263. """
  264. Debug.msg(1, "gcmd.Command(): %s" % ' '.join(cmd))
  265. self.cmd = cmd
  266. self.stderr = stderr
  267. #
  268. # set verbosity level
  269. #
  270. verbose_orig = None
  271. if ('--q' not in self.cmd and '--quiet' not in self.cmd) and \
  272. ('--v' not in self.cmd and '--verbose' not in self.cmd):
  273. if verbose is not None:
  274. if verbose == 0:
  275. self.cmd.append('--quiet')
  276. elif verbose == 3:
  277. self.cmd.append('--verbose')
  278. else:
  279. verbose_orig = os.getenv("GRASS_VERBOSE")
  280. os.environ["GRASS_VERBOSE"] = str(verbose)
  281. #
  282. # create command thread
  283. #
  284. self.cmdThread = CommandThread(cmd, stdin,
  285. stdout, stderr)
  286. self.cmdThread.start()
  287. if wait:
  288. self.cmdThread.join()
  289. if self.cmdThread.module:
  290. self.cmdThread.module.wait()
  291. self.returncode = self.cmdThread.module.returncode
  292. else:
  293. self.returncode = 1
  294. else:
  295. self.cmdThread.join(0.5)
  296. self.returncode = None
  297. if self.returncode is not None:
  298. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" % \
  299. (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
  300. if rerr is not None and self.returncode != 0:
  301. if rerr is False: # GUI dialog
  302. raise GException("%s '%s'%s%s%s %s%s" % \
  303. (_("Execution failed:"),
  304. ' '.join(self.cmd),
  305. os.linesep, os.linesep,
  306. _("Details:"),
  307. os.linesep,
  308. _("Error: ") + self.__GetError()))
  309. elif rerr == sys.stderr: # redirect message to sys
  310. stderr.write("Execution failed: '%s'" % (' '.join(self.cmd)))
  311. stderr.write("%sDetails:%s%s" % (os.linesep,
  312. _("Error: ") + self.__GetError(),
  313. os.linesep))
  314. else:
  315. pass # nop
  316. else:
  317. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" % \
  318. (' '.join(cmd), wait, self.cmdThread.isAlive()))
  319. if verbose_orig:
  320. os.environ["GRASS_VERBOSE"] = verbose_orig
  321. elif "GRASS_VERBOSE" in os.environ:
  322. del os.environ["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 __ReadErrOutput(self):
  338. """!Read standard error output and return list of lines"""
  339. return self.__ReadOutput(self.cmdThread.module.stderr)
  340. def __ProcessStdErr(self):
  341. """
  342. Read messages/warnings/errors from stderr
  343. @return list of (type, message)
  344. """
  345. if self.stderr is None:
  346. lines = self.__ReadErrOutput()
  347. else:
  348. lines = self.cmdThread.error.strip('%s' % os.linesep). \
  349. split('%s' % os.linesep)
  350. msg = []
  351. type = None
  352. content = ""
  353. for line in lines:
  354. if len(line) == 0:
  355. continue
  356. if 'GRASS_' in line: # error or warning
  357. if 'GRASS_INFO_WARNING' in line: # warning
  358. type = "WARNING"
  359. elif 'GRASS_INFO_ERROR' in line: # error
  360. type = "ERROR"
  361. elif 'GRASS_INFO_END': # end of message
  362. msg.append((type, content))
  363. type = None
  364. content = ""
  365. if type:
  366. content += line.split(':', 1)[1].strip()
  367. else: # stderr
  368. msg.append((None, line.strip()))
  369. return msg
  370. def __GetError(self):
  371. """!Get error message or ''"""
  372. if not self.cmdThread.module:
  373. return _("Unable to exectute command: '%s'") % ' '.join(self.cmd)
  374. for type, msg in self.__ProcessStdErr():
  375. if type == 'ERROR':
  376. enc = locale.getdefaultlocale()[1]
  377. if enc:
  378. return unicode(msg, enc)
  379. else:
  380. return msg
  381. return ''
  382. class CommandThread(Thread):
  383. """!Create separate thread for command. Used for commands launched
  384. on the background."""
  385. def __init__ (self, cmd, stdin = None,
  386. stdout = sys.stdout, stderr = sys.stderr):
  387. """
  388. @param cmd command (given as list)
  389. @param stdin standard input stream
  390. @param stdout redirect standard output or None
  391. @param stderr redirect standard error output or None
  392. """
  393. Thread.__init__(self)
  394. self.cmd = cmd
  395. self.stdin = stdin
  396. self.stdout = stdout
  397. self.stderr = stderr
  398. self.module = None
  399. self.error = ''
  400. self._want_abort = False
  401. self.aborted = False
  402. self.setDaemon(True)
  403. # set message formatting
  404. self.message_format = os.getenv("GRASS_MESSAGE_FORMAT")
  405. os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  406. def __del__(self):
  407. if self.message_format:
  408. os.environ["GRASS_MESSAGE_FORMAT"] = self.message_format
  409. else:
  410. del os.environ["GRASS_MESSAGE_FORMAT"]
  411. def run(self):
  412. """!Run command"""
  413. if len(self.cmd) == 0:
  414. return
  415. Debug.msg(1, "gcmd.CommandThread(): %s" % ' '.join(self.cmd))
  416. self.startTime = time.time()
  417. # TODO: replace ugly hack bellow
  418. args = self.cmd
  419. if sys.platform == 'win32':
  420. ext = os.path.splitext(self.cmd[0])[1] == '.py'
  421. if ext or self.cmd[0] in globalvar.grassScripts['.py']:
  422. os.chdir(os.path.join(os.getenv('GISBASE'), 'scripts'))
  423. if not ext:
  424. args = [sys.executable, self.cmd[0] + '.py'] + self.cmd[1:]
  425. else:
  426. args = [sys.executable, self.cmd[0]] + self.cmd[1:]
  427. try:
  428. self.module = Popen(args,
  429. stdin = subprocess.PIPE,
  430. stdout = subprocess.PIPE,
  431. stderr = subprocess.PIPE,
  432. shell = sys.platform == "win32")
  433. except OSError, e:
  434. self.error = str(e)
  435. print >> sys.stderr, e
  436. return 1
  437. if self.stdin: # read stdin if requested ...
  438. self.module.stdin.write(self.stdin)
  439. self.module.stdin.close()
  440. # redirect standard outputs...
  441. self._redirect_stream()
  442. def _redirect_stream(self):
  443. """!Redirect stream"""
  444. if self.stdout:
  445. # make module stdout/stderr non-blocking
  446. out_fileno = self.module.stdout.fileno()
  447. if not subprocess.mswindows:
  448. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  449. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  450. if self.stderr:
  451. # make module stdout/stderr non-blocking
  452. out_fileno = self.module.stderr.fileno()
  453. if not subprocess.mswindows:
  454. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  455. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  456. # wait for the process to end, sucking in stuff until it does end
  457. while self.module.poll() is None:
  458. if self._want_abort: # abort running process
  459. self.module.kill()
  460. self.aborted = True
  461. return
  462. if self.stdout:
  463. line = recv_some(self.module, e = 0, stderr = 0)
  464. self.stdout.write(line)
  465. if self.stderr:
  466. line = recv_some(self.module, e = 0, stderr = 1)
  467. self.stderr.write(line)
  468. if len(line) > 0:
  469. self.error = line
  470. # get the last output
  471. if self.stdout:
  472. line = recv_some(self.module, e = 0, stderr = 0)
  473. self.stdout.write(line)
  474. if self.stderr:
  475. line = recv_some(self.module, e = 0, stderr = 1)
  476. self.stderr.write(line)
  477. if len(line) > 0:
  478. self.error = line
  479. def abort(self):
  480. """!Abort running process, used by main thread to signal an abort"""
  481. self._want_abort = True
  482. def _formatMsg(text):
  483. """!Format error messages for dialogs
  484. """
  485. message = ''
  486. for line in text.splitlines():
  487. if len(line) == 0:
  488. continue
  489. elif 'GRASS_INFO_MESSAGE' in line:
  490. message += line.split(':', 1)[1].strip() + '\n'
  491. elif 'GRASS_INFO_WARNING' in line:
  492. message += line.split(':', 1)[1].strip() + '\n'
  493. elif 'GRASS_INFO_ERROR' in line:
  494. message += line.split(':', 1)[1].strip() + '\n'
  495. elif 'GRASS_INFO_END' in line:
  496. return message
  497. else:
  498. message += line.strip() + '\n'
  499. return message
  500. def RunCommand(prog, flags = "", overwrite = False, quiet = False, verbose = False,
  501. parent = None, read = False, parse = None, stdin = None, getErrorMsg = False, **kwargs):
  502. """!Run GRASS command
  503. @param prog program to run
  504. @param flags flags given as a string
  505. @param overwrite, quiet, verbose flags
  506. @param parent parent window for error messages
  507. @param read fetch stdout
  508. @param parse fn to parse stdout (e.g. grass.parse_key_val) or None
  509. @param stdin stdin or None
  510. @param getErrorMsg get error messages on failure
  511. @param kwargs program parameters
  512. @return returncode (read == False and getErrorMsg == False)
  513. @return returncode, messages (read == False and getErrorMsg == True)
  514. @return stdout (read == True and getErrorMsg == False)
  515. @return returncode, stdout, messages (read == True and getErrorMsg == True)
  516. @return stdout, stderr
  517. """
  518. cmdString = ' '.join(grass.make_command(prog, flags, overwrite,
  519. quiet, verbose, **kwargs))
  520. Debug.msg(1, "gcmd.RunCommand(): %s" % cmdString)
  521. kwargs['stderr'] = subprocess.PIPE
  522. if read:
  523. kwargs['stdout'] = subprocess.PIPE
  524. if stdin:
  525. kwargs['stdin'] = subprocess.PIPE
  526. Debug.msg(2, "gcmd.RunCommand(): command started")
  527. start = time.time()
  528. ps = grass.start_command(GetRealCmd(prog), flags, overwrite, quiet, verbose, **kwargs)
  529. if stdin:
  530. ps.stdin.write(stdin)
  531. ps.stdin.close()
  532. ps.stdin = None
  533. Debug.msg(3, "gcmd.RunCommand(): decoding string")
  534. stdout, stderr = map(DecodeString, ps.communicate())
  535. ret = ps.returncode
  536. Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" % \
  537. (ret, (time.time() - start)))
  538. Debug.msg(3, "gcmd.RunCommand(): print error")
  539. if ret != 0 and parent:
  540. Debug.msg(2, "gcmd.RunCommand(): error %s" % stderr)
  541. if (stderr == None):
  542. Debug.msg(2, "gcmd.RunCommand(): nothing to print ???")
  543. else:
  544. GError(parent = parent,
  545. message = stderr)
  546. Debug.msg(3, "gcmd.RunCommand(): print read error")
  547. if not read:
  548. if not getErrorMsg:
  549. return ret
  550. else:
  551. return ret, _formatMsg(stderr)
  552. if stdout:
  553. Debug.msg(2, "gcmd.RunCommand(): return stdout\n'%s'" % stdout)
  554. else:
  555. Debug.msg(2, "gcmd.RunCommand(): return stdout = None")
  556. if parse:
  557. stdout = parse(stdout)
  558. if not getErrorMsg:
  559. return stdout
  560. Debug.msg(2, "gcmd.RunCommand(): return ret, stdout")
  561. if read and getErrorMsg:
  562. return ret, stdout, _formatMsg(stderr)
  563. Debug.msg(2, "gcmd.RunCommand(): return result")
  564. return stdout, _formatMsg(stderr)