gcmd.py 22 KB

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