gcmd.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  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. from __future__ import print_function
  22. import os
  23. import sys
  24. import time
  25. import errno
  26. import signal
  27. import traceback
  28. import locale
  29. import subprocess
  30. from threading import Thread
  31. import wx
  32. is_mswindows = sys.platform == 'win32'
  33. if is_mswindows:
  34. from win32file import ReadFile, WriteFile
  35. from win32pipe import PeekNamedPipe
  36. import msvcrt
  37. else:
  38. import select
  39. import fcntl
  40. from grass.script import core as grass
  41. from core import globalvar
  42. from core.debug import Debug
  43. # cannot import from the core.utils module to avoid cross dependencies
  44. try:
  45. # intended to be used also outside this module
  46. import gettext
  47. _ = gettext.translation(
  48. 'grasswxpy',
  49. os.path.join(
  50. os.getenv("GISBASE"),
  51. 'locale')).ugettext
  52. except IOError:
  53. # using no translation silently
  54. def null_gettext(string):
  55. return string
  56. _ = null_gettext
  57. if sys.version_info.major == 2:
  58. bytes = str
  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 and isinstance(string, bytes):
  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 is_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 is_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 sys.platform == 'win32':
  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. cmd = Command(cmd=['d.rast', 'elevation.dem'], verbose=3, wait=True)
  291. if cmd.returncode == None:
  292. print 'RUNNING?'
  293. elif cmd.returncode == 0:
  294. print 'SUCCESS'
  295. else:
  296. print 'FAILURE (%d)' % cmd.returncode
  297. """
  298. def __init__(self, cmd, stdin=None,
  299. verbose=None, wait=True, rerr=False,
  300. stdout=None, stderr=None):
  301. """
  302. :param cmd: command given as list
  303. :param stdin: standard input stream
  304. :param verbose: verbose level [0, 3] (--q, --v)
  305. :param wait: wait for child execution terminated
  306. :param rerr: error handling (when GException raised).
  307. True for redirection to stderr, False for GUI
  308. dialog, None for no operation (quiet mode)
  309. :param stdout: redirect standard output or None
  310. :param stderr: redirect standard error output or None
  311. """
  312. Debug.msg(1, "gcmd.Command(): %s" % ' '.join(cmd))
  313. self.cmd = cmd
  314. self.stderr = stderr
  315. #
  316. # set verbosity level
  317. #
  318. verbose_orig = None
  319. if ('--q' not in self.cmd and '--quiet' not in self.cmd) and \
  320. ('--v' not in self.cmd and '--verbose' not in self.cmd):
  321. if verbose is not None:
  322. if verbose == 0:
  323. self.cmd.append('--quiet')
  324. elif verbose == 3:
  325. self.cmd.append('--verbose')
  326. else:
  327. verbose_orig = os.getenv("GRASS_VERBOSE")
  328. os.environ["GRASS_VERBOSE"] = str(verbose)
  329. #
  330. # create command thread
  331. #
  332. self.cmdThread = CommandThread(cmd, stdin,
  333. stdout, stderr)
  334. self.cmdThread.start()
  335. if wait:
  336. self.cmdThread.join()
  337. if self.cmdThread.module:
  338. self.cmdThread.module.wait()
  339. self.returncode = self.cmdThread.module.returncode
  340. else:
  341. self.returncode = 1
  342. else:
  343. self.cmdThread.join(0.5)
  344. self.returncode = None
  345. if self.returncode is not None:
  346. Debug.msg(
  347. 3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" %
  348. (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
  349. if rerr is not None and self.returncode != 0:
  350. if rerr is False: # GUI dialog
  351. raise GException("%s '%s'%s%s%s %s%s" %
  352. (_("Execution failed:"),
  353. ' '.join(self.cmd),
  354. os.linesep, os.linesep,
  355. _("Details:"),
  356. os.linesep,
  357. _("Error: ") + self.__GetError()))
  358. elif rerr == sys.stderr: # redirect message to sys
  359. stderr.write("Execution failed: '%s'" %
  360. (' '.join(self.cmd)))
  361. stderr.write(
  362. "%sDetails:%s%s" %
  363. (os.linesep,
  364. _("Error: ") +
  365. self.__GetError(),
  366. os.linesep))
  367. else:
  368. pass # nop
  369. else:
  370. Debug.msg(
  371. 3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" %
  372. (' '.join(cmd), wait, self.cmdThread.isAlive()))
  373. if verbose_orig:
  374. os.environ["GRASS_VERBOSE"] = verbose_orig
  375. elif "GRASS_VERBOSE" in os.environ:
  376. del os.environ["GRASS_VERBOSE"]
  377. def __ReadOutput(self, stream):
  378. """Read stream and return list of lines
  379. :param stream: stream to be read
  380. """
  381. lineList = []
  382. if stream is None:
  383. return lineList
  384. while True:
  385. line = stream.readline()
  386. if not line:
  387. break
  388. line = line.replace('%s' % os.linesep, '').strip()
  389. lineList.append(line)
  390. return lineList
  391. def __ReadErrOutput(self):
  392. """Read standard error output and return list of lines"""
  393. return self.__ReadOutput(self.cmdThread.module.stderr)
  394. def __ProcessStdErr(self):
  395. """
  396. Read messages/warnings/errors from stderr
  397. :return: list of (type, message)
  398. """
  399. if self.stderr is None:
  400. lines = self.__ReadErrOutput()
  401. else:
  402. lines = self.cmdThread.error.strip('%s' % os.linesep). \
  403. split('%s' % os.linesep)
  404. msg = []
  405. type = None
  406. content = ""
  407. for line in lines:
  408. if len(line) == 0:
  409. continue
  410. if 'GRASS_' in line: # error or warning
  411. if 'GRASS_INFO_WARNING' in line: # warning
  412. type = "WARNING"
  413. elif 'GRASS_INFO_ERROR' in line: # error
  414. type = "ERROR"
  415. elif 'GRASS_INFO_END': # end of message
  416. msg.append((type, content))
  417. type = None
  418. content = ""
  419. if type:
  420. content += line.split(':', 1)[1].strip()
  421. else: # stderr
  422. msg.append((None, line.strip()))
  423. return msg
  424. def __GetError(self):
  425. """Get error message or ''"""
  426. if not self.cmdThread.module:
  427. return _("Unable to exectute command: '%s'") % ' '.join(self.cmd)
  428. for type, msg in self.__ProcessStdErr():
  429. if type == 'ERROR':
  430. if _enc:
  431. return unicode(msg, _enc)
  432. return msg
  433. return ''
  434. class CommandThread(Thread):
  435. """Create separate thread for command. Used for commands launched
  436. on the background."""
  437. def __init__(self, cmd, env=None, stdin=None,
  438. stdout=sys.stdout, stderr=sys.stderr):
  439. """
  440. :param cmd: command (given as list)
  441. :param env: environmental variables
  442. :param stdin: standard input stream
  443. :param stdout: redirect standard output or None
  444. :param stderr: redirect standard error output or None
  445. """
  446. Thread.__init__(self)
  447. self.cmd = cmd
  448. self.stdin = stdin
  449. self.stdout = stdout
  450. self.stderr = stderr
  451. self.env = env
  452. self.module = None
  453. self.error = ''
  454. self._want_abort = False
  455. self.aborted = False
  456. self.setDaemon(True)
  457. # set message formatting
  458. self.message_format = os.getenv("GRASS_MESSAGE_FORMAT")
  459. os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  460. def __del__(self):
  461. if self.message_format:
  462. os.environ["GRASS_MESSAGE_FORMAT"] = self.message_format
  463. else:
  464. del os.environ["GRASS_MESSAGE_FORMAT"]
  465. def run(self):
  466. """Run command"""
  467. if len(self.cmd) == 0:
  468. return
  469. Debug.msg(1, "gcmd.CommandThread(): %s" % ' '.join(self.cmd))
  470. self.startTime = time.time()
  471. # TODO: replace ugly hack below
  472. # this cannot be replaced it can be only improved
  473. # also unifying this with 3 other places in code would be nice
  474. # changing from one chdir to get_real_command function
  475. args = self.cmd
  476. if sys.platform == 'win32':
  477. if os.path.splitext(args[0])[1] == globalvar.SCT_EXT:
  478. args[0] = args[0][:-3]
  479. # using Python executable to run the module if it is a script
  480. # expecting at least module name at first position
  481. # cannot use make_command for this now because it is used in GUI
  482. # The same code is in grass.script.core already twice.
  483. args[0] = grass.get_real_command(args[0])
  484. if args[0].endswith('.py'):
  485. args.insert(0, sys.executable)
  486. try:
  487. self.module = Popen(args,
  488. stdin=subprocess.PIPE,
  489. stdout=subprocess.PIPE,
  490. stderr=subprocess.PIPE,
  491. shell=sys.platform == "win32",
  492. env=self.env)
  493. except OSError as e:
  494. self.error = str(e)
  495. print(e, file=sys.stderr)
  496. return 1
  497. if self.stdin: # read stdin if requested ...
  498. self.module.stdin.write(self.stdin)
  499. self.module.stdin.close()
  500. # redirect standard outputs...
  501. self._redirect_stream()
  502. def _redirect_stream(self):
  503. """Redirect stream"""
  504. if self.stdout:
  505. # make module stdout/stderr non-blocking
  506. out_fileno = self.module.stdout.fileno()
  507. if not is_mswindows:
  508. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  509. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  510. if self.stderr:
  511. # make module stdout/stderr non-blocking
  512. out_fileno = self.module.stderr.fileno()
  513. if not is_mswindows:
  514. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  515. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  516. # wait for the process to end, sucking in stuff until it does end
  517. while self.module.poll() is None:
  518. if self._want_abort: # abort running process
  519. self.module.terminate()
  520. self.aborted = True
  521. return
  522. if self.stdout:
  523. line = recv_some(self.module, e=0, stderr=0)
  524. self.stdout.write(line)
  525. if self.stderr:
  526. line = recv_some(self.module, e=0, stderr=1)
  527. self.stderr.write(line)
  528. if len(line) > 0:
  529. self.error = line
  530. # get the last output
  531. if self.stdout:
  532. line = recv_some(self.module, e=0, stderr=0)
  533. self.stdout.write(line)
  534. if self.stderr:
  535. line = recv_some(self.module, e=0, stderr=1)
  536. self.stderr.write(line)
  537. if len(line) > 0:
  538. self.error = line
  539. def abort(self):
  540. """Abort running process, used by main thread to signal an abort"""
  541. self._want_abort = True
  542. def _formatMsg(text):
  543. """Format error messages for dialogs
  544. """
  545. message = ''
  546. for line in text.splitlines():
  547. if len(line) == 0:
  548. continue
  549. elif 'GRASS_INFO_MESSAGE' in line:
  550. message += line.split(':', 1)[1].strip() + '\n'
  551. elif 'GRASS_INFO_WARNING' in line:
  552. message += line.split(':', 1)[1].strip() + '\n'
  553. elif 'GRASS_INFO_ERROR' in line:
  554. message += line.split(':', 1)[1].strip() + '\n'
  555. elif 'GRASS_INFO_END' in line:
  556. return message
  557. else:
  558. message += line.strip() + '\n'
  559. return message
  560. def RunCommand(prog, flags="", overwrite=False, quiet=False,
  561. verbose=False, parent=None, read=False,
  562. parse=None, stdin=None, getErrorMsg=False, **kwargs):
  563. """Run GRASS command
  564. :param prog: program to run
  565. :param flags: flags given as a string
  566. :param overwrite, quiet, verbose: flags
  567. :param parent: parent window for error messages
  568. :param read: fetch stdout
  569. :param parse: fn to parse stdout (e.g. grass.parse_key_val) or None
  570. :param stdin: stdin or None
  571. :param getErrorMsg: get error messages on failure
  572. :param kwargs: program parameters
  573. :return: returncode (read == False and getErrorMsg == False)
  574. :return: returncode, messages (read == False and getErrorMsg == True)
  575. :return: stdout (read == True and getErrorMsg == False)
  576. :return: returncode, stdout, messages (read == True and getErrorMsg == True)
  577. :return: stdout, stderr
  578. """
  579. cmdString = b' '.join(grass.make_command(prog, flags, overwrite,
  580. quiet, verbose, **kwargs))
  581. Debug.msg(1, "gcmd.RunCommand(): %s" % cmdString)
  582. kwargs['stderr'] = subprocess.PIPE
  583. if read:
  584. kwargs['stdout'] = subprocess.PIPE
  585. if stdin:
  586. kwargs['stdin'] = subprocess.PIPE
  587. if parent:
  588. messageFormat = os.getenv('GRASS_MESSAGE_FORMAT', 'gui')
  589. os.environ['GRASS_MESSAGE_FORMAT'] = 'standard'
  590. start = time.time()
  591. ps = grass.start_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  592. if stdin:
  593. ps.stdin.write(stdin)
  594. ps.stdin.close()
  595. ps.stdin = None
  596. stdout, stderr = list(map(DecodeString, ps.communicate()))
  597. if parent: # restore previous settings
  598. os.environ['GRASS_MESSAGE_FORMAT'] = messageFormat
  599. ret = ps.returncode
  600. Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" %
  601. (ret, (time.time() - start)))
  602. if ret != 0:
  603. if stderr:
  604. Debug.msg(2, "gcmd.RunCommand(): error %s" % stderr)
  605. else:
  606. Debug.msg(2, "gcmd.RunCommand(): nothing to print ???")
  607. if parent:
  608. GError(parent=parent,
  609. caption=_("Error in %s") % prog,
  610. message=stderr)
  611. if not read:
  612. if not getErrorMsg:
  613. return ret
  614. else:
  615. return ret, _formatMsg(stderr)
  616. if stdout:
  617. Debug.msg(3, "gcmd.RunCommand(): return stdout\n'%s'" % stdout)
  618. else:
  619. Debug.msg(3, "gcmd.RunCommand(): return stdout = None")
  620. if parse:
  621. stdout = parse(stdout)
  622. if not getErrorMsg:
  623. return stdout
  624. if read and getErrorMsg:
  625. return ret, stdout, _formatMsg(stderr)
  626. return stdout, _formatMsg(stderr)
  627. def GetDefaultEncoding(forceUTF8=False):
  628. """Get default system encoding
  629. :param bool forceUTF8: force 'UTF-8' if encoding is not defined
  630. :return: system encoding (can be None)
  631. """
  632. enc = locale.getdefaultlocale()[1]
  633. if forceUTF8 and (enc is None or enc == 'UTF8'):
  634. return 'UTF-8'
  635. Debug.msg(1, "GetSystemEncoding(): %s" % enc)
  636. return enc
  637. _enc = GetDefaultEncoding() # define as global variable