gcmd.py 22 KB

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