gcmd.py 23 KB

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