gcmd.py 25 KB

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