gcmd.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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. subprocess.Popen.__init__(self, args, **kwargs)
  139. def recv(self, maxsize = None):
  140. return self._recv('stdout', maxsize)
  141. def recv_err(self, maxsize = None):
  142. return self._recv('stderr', maxsize)
  143. def send_recv(self, input = '', maxsize = None):
  144. return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
  145. def get_conn_maxsize(self, which, maxsize):
  146. if maxsize is None:
  147. maxsize = 1024
  148. elif maxsize < 1:
  149. maxsize = 1
  150. return getattr(self, which), maxsize
  151. def _close(self, which):
  152. getattr(self, which).close()
  153. setattr(self, which, None)
  154. def kill(self):
  155. """Try to kill running process"""
  156. if subprocess.mswindows:
  157. import win32api
  158. handle = win32api.OpenProcess(1, 0, self.pid)
  159. return (0 != win32api.TerminateProcess(handle, 0))
  160. else:
  161. try:
  162. os.kill(-self.pid, signal.SIGTERM) # kill whole group
  163. except OSError:
  164. pass
  165. if subprocess.mswindows:
  166. def send(self, input):
  167. if not self.stdin:
  168. return None
  169. try:
  170. x = msvcrt.get_osfhandle(self.stdin.fileno())
  171. (errCode, written) = WriteFile(x, input)
  172. except ValueError:
  173. return self._close('stdin')
  174. except (subprocess.pywintypes.error, Exception) as why:
  175. if why[0] in (109, errno.ESHUTDOWN):
  176. return self._close('stdin')
  177. raise
  178. return written
  179. def _recv(self, which, maxsize):
  180. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  181. if conn is None:
  182. return None
  183. try:
  184. x = msvcrt.get_osfhandle(conn.fileno())
  185. (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
  186. if maxsize < nAvail:
  187. nAvail = maxsize
  188. if nAvail > 0:
  189. (errCode, read) = ReadFile(x, nAvail, None)
  190. except ValueError:
  191. return self._close(which)
  192. except (subprocess.pywintypes.error, Exception) as why:
  193. if why[0] in (109, errno.ESHUTDOWN):
  194. return self._close(which)
  195. raise
  196. if self.universal_newlines:
  197. read = self._translate_newlines(read)
  198. return read
  199. else:
  200. def send(self, input):
  201. if not self.stdin:
  202. return None
  203. if not select.select([], [self.stdin], [], 0)[1]:
  204. return 0
  205. try:
  206. written = os.write(self.stdin.fileno(), input)
  207. except OSError as why:
  208. if why[0] == errno.EPIPE: #broken pipe
  209. return self._close('stdin')
  210. raise
  211. return written
  212. def _recv(self, which, maxsize):
  213. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  214. if conn is None:
  215. return None
  216. flags = fcntl.fcntl(conn, fcntl.F_GETFL)
  217. if not conn.closed:
  218. fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  219. try:
  220. if not select.select([conn], [], [], 0)[0]:
  221. return ''
  222. r = conn.read(maxsize)
  223. if not r:
  224. return self._close(which)
  225. if self.universal_newlines:
  226. r = self._translate_newlines(r)
  227. return r
  228. finally:
  229. if not conn.closed:
  230. fcntl.fcntl(conn, fcntl.F_SETFL, flags)
  231. message = "Other end disconnected!"
  232. def recv_some(p, t = .1, e = 1, tr = 5, stderr = 0):
  233. if tr < 1:
  234. tr = 1
  235. x = time.time()+t
  236. y = []
  237. r = ''
  238. pr = p.recv
  239. if stderr:
  240. pr = p.recv_err
  241. while time.time() < x or r:
  242. r = pr()
  243. if r is None:
  244. if e:
  245. raise Exception(message)
  246. else:
  247. break
  248. elif r:
  249. y.append(r)
  250. else:
  251. time.sleep(max((x-time.time())/tr, 0))
  252. return ''.join(y)
  253. def send_all(p, data):
  254. while len(data):
  255. sent = p.send(data)
  256. if sent is None:
  257. raise Exception(message)
  258. data = buffer(data, sent)
  259. class Command:
  260. """Run command in separate thread. Used for commands launched
  261. on the background.
  262. If stdout/err is redirected, write() method is required for the
  263. given classes.
  264. cmd = Command(cmd=['d.rast', 'elevation.dem'], verbose=3, wait=True)
  265. if cmd.returncode == None:
  266. print 'RUNNING?'
  267. elif cmd.returncode == 0:
  268. print 'SUCCESS'
  269. else:
  270. print 'FAILURE (%d)' % cmd.returncode
  271. """
  272. def __init__ (self, cmd, stdin = None,
  273. verbose = None, wait = True, rerr = False,
  274. stdout = None, stderr = None):
  275. """
  276. :param cmd: command given as list
  277. :param stdin: standard input stream
  278. :param verbose: verbose level [0, 3] (--q, --v)
  279. :param wait: wait for child execution terminated
  280. :param rerr: error handling (when GException raised).
  281. True for redirection to stderr, False for GUI
  282. dialog, None for no operation (quiet mode)
  283. :param stdout: redirect standard output or None
  284. :param stderr: redirect standard error output or None
  285. """
  286. Debug.msg(1, "gcmd.Command(): %s" % ' '.join(cmd))
  287. self.cmd = cmd
  288. self.stderr = stderr
  289. #
  290. # set verbosity level
  291. #
  292. verbose_orig = None
  293. if ('--q' not in self.cmd and '--quiet' not in self.cmd) and \
  294. ('--v' not in self.cmd and '--verbose' not in self.cmd):
  295. if verbose is not None:
  296. if verbose == 0:
  297. self.cmd.append('--quiet')
  298. elif verbose == 3:
  299. self.cmd.append('--verbose')
  300. else:
  301. verbose_orig = os.getenv("GRASS_VERBOSE")
  302. os.environ["GRASS_VERBOSE"] = str(verbose)
  303. #
  304. # create command thread
  305. #
  306. self.cmdThread = CommandThread(cmd, stdin,
  307. stdout, stderr)
  308. self.cmdThread.start()
  309. if wait:
  310. self.cmdThread.join()
  311. if self.cmdThread.module:
  312. self.cmdThread.module.wait()
  313. self.returncode = self.cmdThread.module.returncode
  314. else:
  315. self.returncode = 1
  316. else:
  317. self.cmdThread.join(0.5)
  318. self.returncode = None
  319. if self.returncode is not None:
  320. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" % \
  321. (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
  322. if rerr is not None and self.returncode != 0:
  323. if rerr is False: # GUI dialog
  324. raise GException("%s '%s'%s%s%s %s%s" % \
  325. (_("Execution failed:"),
  326. ' '.join(self.cmd),
  327. os.linesep, os.linesep,
  328. _("Details:"),
  329. os.linesep,
  330. _("Error: ") + self.__GetError()))
  331. elif rerr == sys.stderr: # redirect message to sys
  332. stderr.write("Execution failed: '%s'" % (' '.join(self.cmd)))
  333. stderr.write("%sDetails:%s%s" % (os.linesep,
  334. _("Error: ") + self.__GetError(),
  335. os.linesep))
  336. else:
  337. pass # nop
  338. else:
  339. Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" % \
  340. (' '.join(cmd), wait, self.cmdThread.isAlive()))
  341. if verbose_orig:
  342. os.environ["GRASS_VERBOSE"] = verbose_orig
  343. elif "GRASS_VERBOSE" in os.environ:
  344. del os.environ["GRASS_VERBOSE"]
  345. def __ReadOutput(self, stream):
  346. """Read stream and return list of lines
  347. :param stream: stream to be read
  348. """
  349. lineList = []
  350. if stream is None:
  351. return lineList
  352. while True:
  353. line = stream.readline()
  354. if not line:
  355. break
  356. line = line.replace('%s' % os.linesep, '').strip()
  357. lineList.append(line)
  358. return lineList
  359. def __ReadErrOutput(self):
  360. """Read standard error output and return list of lines"""
  361. return self.__ReadOutput(self.cmdThread.module.stderr)
  362. def __ProcessStdErr(self):
  363. """
  364. Read messages/warnings/errors from stderr
  365. :return: list of (type, message)
  366. """
  367. if self.stderr is None:
  368. lines = self.__ReadErrOutput()
  369. else:
  370. lines = self.cmdThread.error.strip('%s' % os.linesep). \
  371. split('%s' % os.linesep)
  372. msg = []
  373. type = None
  374. content = ""
  375. for line in lines:
  376. if len(line) == 0:
  377. continue
  378. if 'GRASS_' in line: # error or warning
  379. if 'GRASS_INFO_WARNING' in line: # warning
  380. type = "WARNING"
  381. elif 'GRASS_INFO_ERROR' in line: # error
  382. type = "ERROR"
  383. elif 'GRASS_INFO_END': # end of message
  384. msg.append((type, content))
  385. type = None
  386. content = ""
  387. if type:
  388. content += line.split(':', 1)[1].strip()
  389. else: # stderr
  390. msg.append((None, line.strip()))
  391. return msg
  392. def __GetError(self):
  393. """Get error message or ''"""
  394. if not self.cmdThread.module:
  395. return _("Unable to exectute command: '%s'") % ' '.join(self.cmd)
  396. for type, msg in self.__ProcessStdErr():
  397. if type == 'ERROR':
  398. if _enc:
  399. return unicode(msg, _enc)
  400. return msg
  401. return ''
  402. class CommandThread(Thread):
  403. """Create separate thread for command. Used for commands launched
  404. on the background."""
  405. def __init__ (self, cmd, env = None, stdin = None,
  406. stdout = sys.stdout, stderr = sys.stderr):
  407. """
  408. :param cmd: command (given as list)
  409. :param env: environmental variables
  410. :param stdin: standard input stream
  411. :param stdout: redirect standard output or None
  412. :param stderr: redirect standard error output or None
  413. """
  414. Thread.__init__(self)
  415. self.cmd = cmd
  416. self.stdin = stdin
  417. self.stdout = stdout
  418. self.stderr = stderr
  419. self.env = env
  420. self.module = None
  421. self.error = ''
  422. self._want_abort = False
  423. self.aborted = False
  424. self.setDaemon(True)
  425. # set message formatting
  426. self.message_format = os.getenv("GRASS_MESSAGE_FORMAT")
  427. os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
  428. def __del__(self):
  429. if self.message_format:
  430. os.environ["GRASS_MESSAGE_FORMAT"] = self.message_format
  431. else:
  432. del os.environ["GRASS_MESSAGE_FORMAT"]
  433. def run(self):
  434. """Run command"""
  435. if len(self.cmd) == 0:
  436. return
  437. Debug.msg(1, "gcmd.CommandThread(): %s" % ' '.join(self.cmd))
  438. self.startTime = time.time()
  439. # TODO: replace ugly hack below
  440. # this cannot be replaced it can be only improved
  441. # also unifying this with 3 other places in code would be nice
  442. # changing from one chdir to get_real_command function
  443. args = self.cmd
  444. if sys.platform == 'win32':
  445. if os.path.splitext(args[0])[1] == globalvar.SCT_EXT:
  446. args[0] = args[0][:-3]
  447. # using Python executable to run the module if it is a script
  448. # expecting at least module name at first position
  449. # cannot use make_command for this now because it is used in GUI
  450. # The same code is in grass.script.core already twice.
  451. args[0] = grass.get_real_command(args[0])
  452. if args[0].endswith('.py'):
  453. args.insert(0, sys.executable)
  454. try:
  455. self.module = Popen(args,
  456. stdin = subprocess.PIPE,
  457. stdout = subprocess.PIPE,
  458. stderr = subprocess.PIPE,
  459. shell = sys.platform == "win32",
  460. env = self.env)
  461. except OSError as e:
  462. self.error = str(e)
  463. print >> sys.stderr, e
  464. return 1
  465. if self.stdin: # read stdin if requested ...
  466. self.module.stdin.write(self.stdin)
  467. self.module.stdin.close()
  468. # redirect standard outputs...
  469. self._redirect_stream()
  470. def _redirect_stream(self):
  471. """Redirect stream"""
  472. if self.stdout:
  473. # make module stdout/stderr non-blocking
  474. out_fileno = self.module.stdout.fileno()
  475. if not subprocess.mswindows:
  476. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  477. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  478. if self.stderr:
  479. # make module stdout/stderr non-blocking
  480. out_fileno = self.module.stderr.fileno()
  481. if not subprocess.mswindows:
  482. flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
  483. fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  484. # wait for the process to end, sucking in stuff until it does end
  485. while self.module.poll() is None:
  486. if self._want_abort: # abort running process
  487. self.module.terminate()
  488. self.aborted = True
  489. return
  490. if self.stdout:
  491. line = recv_some(self.module, e = 0, stderr = 0)
  492. self.stdout.write(line)
  493. if self.stderr:
  494. line = recv_some(self.module, e = 0, stderr = 1)
  495. self.stderr.write(line)
  496. if len(line) > 0:
  497. self.error = line
  498. # get the last output
  499. if self.stdout:
  500. line = recv_some(self.module, e = 0, stderr = 0)
  501. self.stdout.write(line)
  502. if self.stderr:
  503. line = recv_some(self.module, e = 0, stderr = 1)
  504. self.stderr.write(line)
  505. if len(line) > 0:
  506. self.error = line
  507. def abort(self):
  508. """Abort running process, used by main thread to signal an abort"""
  509. self._want_abort = True
  510. def _formatMsg(text):
  511. """Format error messages for dialogs
  512. """
  513. message = ''
  514. for line in text.splitlines():
  515. if len(line) == 0:
  516. continue
  517. elif 'GRASS_INFO_MESSAGE' in line:
  518. message += line.split(':', 1)[1].strip() + '\n'
  519. elif 'GRASS_INFO_WARNING' in line:
  520. message += line.split(':', 1)[1].strip() + '\n'
  521. elif 'GRASS_INFO_ERROR' in line:
  522. message += line.split(':', 1)[1].strip() + '\n'
  523. elif 'GRASS_INFO_END' in line:
  524. return message
  525. else:
  526. message += line.strip() + '\n'
  527. return message
  528. def RunCommand(prog, flags = "", overwrite = False, quiet = False,
  529. verbose = False, parent = None, read = False,
  530. parse = None, stdin = None, getErrorMsg = False, **kwargs):
  531. """Run GRASS command
  532. :param prog: program to run
  533. :param flags: flags given as a string
  534. :param overwrite, quiet, verbose: flags
  535. :param parent: parent window for error messages
  536. :param read: fetch stdout
  537. :param parse: fn to parse stdout (e.g. grass.parse_key_val) or None
  538. :param stdin: stdin or None
  539. :param getErrorMsg: get error messages on failure
  540. :param kwargs: program parameters
  541. :return: returncode (read == False and getErrorMsg == False)
  542. :return: returncode, messages (read == False and getErrorMsg == True)
  543. :return: stdout (read == True and getErrorMsg == False)
  544. :return: returncode, stdout, messages (read == True and getErrorMsg == True)
  545. :return: stdout, stderr
  546. """
  547. cmdString = ' '.join(grass.make_command(prog, flags, overwrite,
  548. quiet, verbose, **kwargs))
  549. Debug.msg(1, "gcmd.RunCommand(): %s" % cmdString)
  550. kwargs['stderr'] = subprocess.PIPE
  551. if read:
  552. kwargs['stdout'] = subprocess.PIPE
  553. if stdin:
  554. kwargs['stdin'] = subprocess.PIPE
  555. if parent:
  556. messageFormat = os.getenv('GRASS_MESSAGE_FORMAT', 'gui')
  557. os.environ['GRASS_MESSAGE_FORMAT'] = 'standard'
  558. Debug.msg(2, "gcmd.RunCommand(): command started")
  559. start = time.time()
  560. ps = grass.start_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  561. if stdin:
  562. ps.stdin.write(stdin)
  563. ps.stdin.close()
  564. ps.stdin = None
  565. Debug.msg(3, "gcmd.RunCommand(): decoding string")
  566. stdout, stderr = map(DecodeString, ps.communicate())
  567. if parent: # restore previous settings
  568. os.environ['GRASS_MESSAGE_FORMAT'] = messageFormat
  569. ret = ps.returncode
  570. Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" % \
  571. (ret, (time.time() - start)))
  572. Debug.msg(3, "gcmd.RunCommand(): print error")
  573. if ret != 0:
  574. if stderr:
  575. Debug.msg(2, "gcmd.RunCommand(): error %s" % stderr)
  576. else:
  577. Debug.msg(2, "gcmd.RunCommand(): nothing to print ???")
  578. if parent:
  579. GError(parent = parent,
  580. caption = _("Error in %s") % prog,
  581. message = stderr)
  582. Debug.msg(3, "gcmd.RunCommand(): print read error")
  583. if not read:
  584. if not getErrorMsg:
  585. return ret
  586. else:
  587. return ret, _formatMsg(stderr)
  588. if stdout:
  589. Debug.msg(2, "gcmd.RunCommand(): return stdout\n'%s'" % stdout)
  590. else:
  591. Debug.msg(2, "gcmd.RunCommand(): return stdout = None")
  592. if parse:
  593. stdout = parse(stdout)
  594. if not getErrorMsg:
  595. return stdout
  596. Debug.msg(2, "gcmd.RunCommand(): return ret, stdout")
  597. if read and getErrorMsg:
  598. return ret, stdout, _formatMsg(stderr)
  599. Debug.msg(2, "gcmd.RunCommand(): return result")
  600. return stdout, _formatMsg(stderr)
  601. def GetDefaultEncoding(forceUTF8 = False):
  602. """Get default system encoding
  603. :param bool forceUTF8: force 'UTF-8' if encoding is not defined
  604. :return: system encoding (can be None)
  605. """
  606. enc = locale.getdefaultlocale()[1]
  607. if forceUTF8 and (enc is None or enc == 'UTF8'):
  608. return 'UTF-8'
  609. Debug.msg(1, "GetSystemEncoding(): %s" % enc)
  610. return enc
  611. _enc = GetDefaultEncoding() # define as global variable