gcmd.py 20 KB

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