gcmd.py 24 KB

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