core.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. """!@package grass.script.core
  2. @brief GRASS Python scripting module
  3. Core functions to be used in Python scripts.
  4. Usage:
  5. @code
  6. from grass.script import core as grass
  7. grass.parser()
  8. ...
  9. @endcode
  10. (C) 2008-2009 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Glynn Clements
  15. @author Martin Landa <landa.martin gmail.com>
  16. @author Michael Barton <michael.barton@asu.edu>
  17. """
  18. import os
  19. import sys
  20. import types
  21. import re
  22. import atexit
  23. import subprocess
  24. # i18N
  25. import gettext
  26. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  27. # subprocess wrapper that uses shell on Windows
  28. class Popen(subprocess.Popen):
  29. def __init__(self, args, bufsize=0, executable=None,
  30. stdin=None, stdout=None, stderr=None,
  31. preexec_fn=None, close_fds=False, shell=None,
  32. cwd=None, env=None, universal_newlines=False,
  33. startupinfo=None, creationflags=0):
  34. if shell == None:
  35. shell = (sys.platform == "win32")
  36. subprocess.Popen.__init__(self, args, bufsize, executable,
  37. stdin, stdout, stderr,
  38. preexec_fn, close_fds, shell,
  39. cwd, env, universal_newlines,
  40. startupinfo, creationflags)
  41. PIPE = subprocess.PIPE
  42. STDOUT = subprocess.STDOUT
  43. fatal_exit = True # abort on fatal()
  44. def call(*args, **kwargs):
  45. return Popen(*args, **kwargs).wait()
  46. # GRASS-oriented interface to subprocess module
  47. _popen_args = ["bufsize", "executable", "stdin", "stdout", "stderr",
  48. "preexec_fn", "close_fds", "cwd", "env",
  49. "universal_newlines", "startupinfo", "creationflags"]
  50. def _make_val(val):
  51. if isinstance(val, types.StringType):
  52. return val
  53. if isinstance(val, types.ListType):
  54. return ",".join(map(_make_val, val))
  55. if isinstance(val, types.TupleType):
  56. return _make_val(list(val))
  57. return str(val)
  58. def make_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **options):
  59. """!Return a list of strings suitable for use as the args parameter to
  60. Popen() or call(). Example:
  61. @code
  62. >>> grass.make_command("g.message", flags = 'w', message = 'this is a warning')
  63. ['g.message', '-w', 'message=this is a warning']
  64. @endcode
  65. @param prog GRASS module
  66. @param flags flags to be used
  67. @param overwrite True to enable overwriting the output (--o)
  68. @param quiet run quietly (--q)
  69. @param verbose run verbosely (--v)
  70. @param options
  71. @return list of arguments
  72. """
  73. args = [prog]
  74. if overwrite:
  75. args.append("--o")
  76. if quiet:
  77. args.append("--q")
  78. if verbose:
  79. args.append("--v")
  80. if flags:
  81. args.append("-%s" % flags)
  82. for opt, val in options.iteritems():
  83. if val != None:
  84. if opt[0] == '_':
  85. opt = opt[1:]
  86. args.append("%s=%s" % (opt, _make_val(val)))
  87. return args
  88. def start_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, **kwargs):
  89. """!Returns a Popen object with the command created by make_command.
  90. Accepts any of the arguments which Popen() accepts apart from "args"
  91. and "shell".
  92. \code
  93. >>> p = grass.start_command("g.gisenv", stdout = subprocess.PIPE)
  94. >>> print p
  95. <subprocess.Popen object at 0xb7c12f6c>
  96. >>> print p.communicate()[0]
  97. GISDBASE='/opt/grass-data';
  98. LOCATION_NAME='spearfish60';
  99. MAPSET='glynn';
  100. GRASS_DB_ENCODING='ascii';
  101. GRASS_GUI='text';
  102. MONITOR='x0';
  103. \endcode
  104. @param prog GRASS module
  105. @param flags flags to be used
  106. @param overwrite True to enable overwriting the output (--o)
  107. @param quiet run quietly (--q)
  108. @param verbose run verbosely (--v)
  109. @param kwargs
  110. @return Popen object
  111. """
  112. options = {}
  113. popts = {}
  114. for opt, val in kwargs.iteritems():
  115. if opt in _popen_args:
  116. popts[opt] = val
  117. else:
  118. options[opt] = val
  119. args = make_command(prog, flags, overwrite, quiet, verbose, **options)
  120. return Popen(args, **popts)
  121. def run_command(*args, **kwargs):
  122. """!Passes all arguments to start_command, then waits for the process to
  123. complete, returning its exit code. Similar to subprocess.call(), but
  124. with the make_command() interface.
  125. @param args
  126. @param kwargs
  127. @return exit code
  128. """
  129. ps = start_command(*args, **kwargs)
  130. return ps.wait()
  131. def pipe_command(*args, **kwargs):
  132. """!Passes all arguments to start_command, but also adds
  133. "stdout = PIPE". Returns the Popen object.
  134. \code
  135. >>> p = grass.pipe_command("g.gisenv")
  136. >>> print p
  137. <subprocess.Popen object at 0xb7c12f6c>
  138. >>> print p.communicate()[0]
  139. GISDBASE='/opt/grass-data';
  140. LOCATION_NAME='spearfish60';
  141. MAPSET='glynn';
  142. GRASS_DB_ENCODING='ascii';
  143. GRASS_GUI='text';
  144. MONITOR='x0';
  145. \endcode
  146. @param args
  147. @param kwargs
  148. @return Popen object
  149. """
  150. kwargs['stdout'] = PIPE
  151. return start_command(*args, **kwargs)
  152. def feed_command(*args, **kwargs):
  153. """!Passes all arguments to start_command, but also adds
  154. "stdin = PIPE". Returns the Popen object.
  155. @param args
  156. @param kwargs
  157. @return Popen object
  158. """
  159. kwargs['stdin'] = PIPE
  160. return start_command(*args, **kwargs)
  161. def read_command(*args, **kwargs):
  162. """!Passes all arguments to pipe_command, then waits for the process to
  163. complete, returning its stdout (i.e. similar to shell `backticks`).
  164. @param args
  165. @param kwargs
  166. @return stdout
  167. """
  168. ps = pipe_command(*args, **kwargs)
  169. return ps.communicate()[0]
  170. def parse_command(*args, **kwargs):
  171. """!Passes all arguments to read_command, then parses the output by
  172. parse_key_val().
  173. Parsing function can be optionally given by <b>parse</b> parameter
  174. including its arguments, e.g.
  175. @code
  176. parse_command(..., parse = (grass.parse_key_val, { 'sep' : ':' }))
  177. @endcode
  178. @param args
  179. @param kwargs
  180. @return parsed module output
  181. """
  182. parse = None
  183. if kwargs.has_key('parse'):
  184. if type(kwargs['parse']) is types.TupleType:
  185. parse = kwargs['parse'][0]
  186. parse_args = kwargs['parse'][1]
  187. del kwargs['parse']
  188. if not parse:
  189. parse = parse_key_val # use default fn
  190. parse_args = {}
  191. res = read_command(*args, **kwargs)
  192. return parse(res, **parse_args)
  193. def write_command(*args, **kwargs):
  194. """!Passes all arguments to feed_command, with the string specified
  195. by the 'stdin' argument fed to the process' stdin.
  196. @param args
  197. @param kwargs
  198. @return return code
  199. """
  200. stdin = kwargs['stdin']
  201. p = feed_command(*args, **kwargs)
  202. p.stdin.write(stdin)
  203. p.stdin.close()
  204. return p.wait()
  205. def exec_command(prog, flags = "", overwrite = False, quiet = False, verbose = False, env = None, **kwargs):
  206. """!Interface to os.execvpe(), but with the make_command() interface.
  207. @param prog GRASS module
  208. @param flags flags to be used
  209. @param overwrite True to enable overwriting the output (--o)
  210. @param quiet run quietly (--q)
  211. @param verbose run verbosely (--v)
  212. @param env environment variable (default os.environ)
  213. @param kwargs
  214. """
  215. args = make_command(prog, flags, overwrite, quiet, verbose, **kwargs)
  216. if env == None:
  217. env = os.environ
  218. os.execvpe(prog, args, env)
  219. # interface to g.message
  220. def message(msg, flag = None):
  221. """!Display a message using g.message
  222. @param msg message to be displayed
  223. @param flag flags (given as string)
  224. """
  225. run_command("g.message", flags = flag, message = msg)
  226. def debug(msg, debug = 1):
  227. """!Display a debugging message using g.message -d
  228. @param msg message to be displayed
  229. @param debug debug level (0-5)
  230. """
  231. run_command("g.message", flags = 'd', message = msg, debug = debug)
  232. def verbose(msg):
  233. """!Display a verbose message using g.message -v
  234. @param msg message to be displayed
  235. """
  236. message(msg, flag = 'v')
  237. def info(msg):
  238. """!Display an informational message using g.message -i
  239. @param msg message to be displayed
  240. """
  241. message(msg, flag = 'i')
  242. def warning(msg):
  243. """!Display a warning message using g.message -w
  244. @param msg warning message to be displayed
  245. """
  246. message(msg, flag = 'w')
  247. def error(msg):
  248. """!Display an error message using g.message -e
  249. @param msg error message to be displayed
  250. """
  251. message(msg, flag = 'e')
  252. def fatal(msg):
  253. """!Display an error message using g.message -e, then abort
  254. @param msg error message to be displayed
  255. """
  256. error(msg)
  257. global fatal_exit
  258. if fatal_exit:
  259. sys.exit(1)
  260. def set_fatal_exit(exit = True):
  261. """!Set fatal_exit variable
  262. @param exit True to abort on fatal() otherwise just error message
  263. is printed"""
  264. global fatal_exit
  265. fatal_exit = exit
  266. # interface to g.parser
  267. def _parse_opts(lines):
  268. options = {}
  269. flags = {}
  270. for line in lines:
  271. line = line.rstrip('\r\n')
  272. if not line:
  273. break
  274. try:
  275. [var, val] = line.split('=', 1)
  276. except:
  277. raise SyntaxError("invalid output from g.parser: %s" % line)
  278. if var.startswith('flag_'):
  279. flags[var[5:]] = bool(int(val))
  280. elif var.startswith('opt_'):
  281. options[var[4:]] = val
  282. elif var in ['GRASS_OVERWRITE', 'GRASS_VERBOSE']:
  283. os.environ[var] = val
  284. else:
  285. raise SyntaxError("invalid output from g.parser: %s" % line)
  286. return (options, flags)
  287. def parser():
  288. """!Interface to g.parser, intended to be run from the top-level, e.g.:
  289. @code
  290. if __name__ == "__main__":
  291. options, flags = grass.parser()
  292. main()
  293. @endcode
  294. Thereafter, the global variables "options" and "flags" will be
  295. dictionaries containing option/flag values, keyed by lower-case
  296. option/flag names. The values in "options" are strings, those in
  297. "flags" are Python booleans.
  298. """
  299. if not os.getenv("GISBASE"):
  300. print >> sys.stderr, "You must be in GRASS GIS to run this program."
  301. sys.exit(1)
  302. cmdline = [basename(sys.argv[0])]
  303. cmdline += ['"' + arg + '"' for arg in sys.argv[1:]]
  304. os.environ['CMDLINE'] = ' '.join(cmdline)
  305. argv = sys.argv[:]
  306. name = argv[0]
  307. if not os.path.isabs(name):
  308. if os.sep in name or (os.altsep and os.altsep in name):
  309. argv[0] = os.path.abspath(name)
  310. else:
  311. argv[0] = os.path.join(sys.path[0], name)
  312. p = Popen(['g.parser', '-s'] + argv, stdout = PIPE)
  313. s = p.communicate()[0]
  314. lines = s.splitlines()
  315. if not lines or lines[0].rstrip('\r\n') != "@ARGS_PARSED@":
  316. sys.stdout.write(s)
  317. sys.exit()
  318. return _parse_opts(lines[1:])
  319. # interface to g.tempfile
  320. def tempfile():
  321. """!Returns the name of a temporary file, created with g.tempfile."""
  322. return read_command("g.tempfile", pid = os.getpid()).strip()
  323. # key-value parsers
  324. def parse_key_val(s, sep = '=', dflt = None, val_type = None, vsep = None):
  325. """!Parse a string into a dictionary, where entries are separated
  326. by newlines and the key and value are separated by `sep' (default: `=')
  327. @param s string to be parsed
  328. @param sep key/value separator
  329. @param dflt default value to be used
  330. @param val_type value type (None for no cast)
  331. @param vsep vertical separator (default os.linesep)
  332. @return parsed input (dictionary of keys/values)
  333. """
  334. result = {}
  335. if not s:
  336. return result
  337. if vsep:
  338. lines = s.split(vsep)
  339. try:
  340. lines.remove('\n')
  341. except ValueError:
  342. pass
  343. else:
  344. lines = s.splitlines()
  345. for line in lines:
  346. kv = line.split(sep, 1)
  347. k = kv[0].strip()
  348. if len(kv) > 1:
  349. v = kv[1]
  350. else:
  351. v = dflt
  352. if val_type:
  353. result[k] = val_type(v)
  354. else:
  355. result[k] = v
  356. return result
  357. # interface to g.gisenv
  358. def gisenv():
  359. """!Returns the output from running g.gisenv (with no arguments), as a
  360. dictionary. Example:
  361. \code
  362. >>> env = grass.gisenv()
  363. >>> print env['GISDBASE']
  364. /opt/grass-data
  365. \endcode
  366. @return list of GRASS variables
  367. """
  368. s = read_command("g.gisenv", flags='n')
  369. return parse_key_val(s)
  370. # interface to g.region
  371. def region():
  372. """!Returns the output from running "g.region -g", as a
  373. dictionary. Example:
  374. \code
  375. >>> region = grass.region()
  376. >>> [region[key] for key in "nsew"]
  377. ['4928000', '4914020', '609000', '590010']
  378. >>> (region['nsres'], region['ewres'])
  379. ('30', '30')
  380. \endcode
  381. @return dictionary of region values
  382. """
  383. s = read_command("g.region", flags='g')
  384. reg = parse_key_val(s, val_type = float)
  385. for k in ['rows', 'cols']:
  386. reg[k] = int(reg[k])
  387. return reg
  388. def use_temp_region():
  389. """!Copies the current region to a temporary region with "g.region save=",
  390. then sets WIND_OVERRIDE to refer to that region. Installs an atexit
  391. handler to delete the temporary region upon termination.
  392. """
  393. name = "tmp.%s.%d" % (os.path.basename(sys.argv[0]), os.getpid())
  394. run_command("g.region", save = name)
  395. os.environ['WIND_OVERRIDE'] = name
  396. atexit.register(del_temp_region)
  397. def del_temp_region():
  398. """!Unsets WIND_OVERRIDE and removes any region named by it."""
  399. try:
  400. name = os.environ.pop('WIND_OVERRIDE')
  401. run_command("g.remove", quiet = True, region = name)
  402. except:
  403. pass
  404. # interface to g.findfile
  405. def find_file(name, element = 'cell', mapset = None):
  406. """!Returns the output from running g.findfile as a
  407. dictionary. Example:
  408. \code
  409. >>> result = grass.find_file('fields', element = 'vector')
  410. >>> print result['fullname']
  411. fields@PERMANENT
  412. >>> print result['file']
  413. /opt/grass-data/spearfish60/PERMANENT/vector/fields
  414. \endcode
  415. @param name file name
  416. @param element element type (default 'cell')
  417. @param mapset mapset name (default all mapsets in search path)
  418. @return parsed output of g.findfile
  419. """
  420. s = read_command("g.findfile", flags='n', element = element, file = name, mapset = mapset)
  421. return parse_key_val(s)
  422. # interface to g.list
  423. def list_grouped(type):
  424. """!Returns the output from running g.list, as a dictionary where the keys
  425. are mapset names and the values are lists of maps in that mapset. Example:
  426. \code
  427. >>> grass.list_grouped('rast')['PERMANENT']
  428. ['aspect', 'erosion1', 'quads', 'soils', 'strm.dist', ...
  429. \endcode
  430. @param type element type
  431. """
  432. dashes_re = re.compile("^----+$")
  433. mapset_re = re.compile("<(.*)>")
  434. result = {}
  435. mapset = None
  436. for line in read_command("g.list", type = type).splitlines():
  437. if line == "":
  438. continue
  439. if dashes_re.match(line):
  440. continue
  441. m = mapset_re.search(line)
  442. if m:
  443. mapset = m.group(1)
  444. result[mapset] = []
  445. continue
  446. if mapset:
  447. result[mapset].extend(line.split())
  448. return result
  449. def mlist_grouped(type, mapset = None, pattern = None):
  450. """!Returns the output from running g.mlist, as a dictionary where the keys
  451. are mapset names and the values are lists of maps in that mapset.
  452. @param type element type
  453. @param mapset mapset name (default all mapset in search path)
  454. @param pattern pattern string
  455. """
  456. result = {}
  457. mapset_element = None
  458. for line in read_command("g.mlist", flags="m",
  459. type = type, mapset = mapset, pattern = pattern).splitlines():
  460. try:
  461. map, mapset_element = line.split('@')
  462. except ValueError:
  463. print >> sys.stderr, "Invalid element '%s'" % line
  464. continue
  465. if result.has_key(mapset_element):
  466. result[mapset_element].append(map)
  467. else:
  468. result[mapset_element] = [map, ]
  469. return result
  470. def _concat(xs):
  471. result = []
  472. for x in xs:
  473. result.extend(x)
  474. return result
  475. def list_pairs(type):
  476. """!Returns the output from running g.list, as a list of (map, mapset)
  477. pairs. Example:
  478. \code
  479. >>> grass.list_pairs('rast')
  480. [('aspect', 'PERMANENT'), ('erosion1', 'PERMANENT'), ('quads', 'PERMANENT'), ...
  481. \endcode
  482. @param type element type
  483. @return list of tuples (map, mapset)
  484. """
  485. return _concat([[(map, mapset) for map in maps]
  486. for mapset, maps in list_grouped(type).iteritems()])
  487. def list_strings(type):
  488. """!Returns the output from running g.list, as a list of qualified
  489. names. Example:
  490. \code
  491. >>> grass.list_strings('rast')
  492. ['aspect@PERMANENT', 'erosion1@PERMANENT', 'quads@PERMANENT', 'soils@PERMANENT', ...
  493. \endcode
  494. @param type element type
  495. @return list of strings ('map@@mapset')
  496. """
  497. return ["%s@%s" % pair for pair in list_pairs(type)]
  498. # color parsing
  499. named_colors = {
  500. "white": (1.00, 1.00, 1.00),
  501. "black": (0.00, 0.00, 0.00),
  502. "red": (1.00, 0.00, 0.00),
  503. "green": (0.00, 1.00, 0.00),
  504. "blue": (0.00, 0.00, 1.00),
  505. "yellow": (1.00, 1.00, 0.00),
  506. "magenta": (1.00, 0.00, 1.00),
  507. "cyan": (0.00, 1.00, 1.00),
  508. "aqua": (0.00, 0.75, 0.75),
  509. "grey": (0.75, 0.75, 0.75),
  510. "gray": (0.75, 0.75, 0.75),
  511. "orange": (1.00, 0.50, 0.00),
  512. "brown": (0.75, 0.50, 0.25),
  513. "purple": (0.50, 0.00, 1.00),
  514. "violet": (0.50, 0.00, 1.00),
  515. "indigo": (0.00, 0.50, 1.00)}
  516. def parse_color(val, dflt = None):
  517. """!Parses the string "val" as a GRASS colour, which can be either one of
  518. the named colours or an R:G:B tuple e.g. 255:255:255. Returns an
  519. (r,g,b) triple whose components are floating point values between 0
  520. and 1. Example:
  521. \code
  522. >>> grass.parse_color("red")
  523. (1.0, 0.0, 0.0)
  524. >>> grass.parse_color("255:0:0")
  525. (1.0, 0.0, 0.0)
  526. \endcode
  527. @param val color value
  528. @param dflt default color value
  529. @return tuple RGB
  530. """
  531. if val in named_colors:
  532. return named_colors[val]
  533. vals = val.split(':')
  534. if len(vals) == 3:
  535. return tuple(float(v) / 255 for v in vals)
  536. return dflt
  537. # check GRASS_OVERWRITE
  538. def overwrite():
  539. """!Return True if existing files may be overwritten"""
  540. owstr = 'GRASS_OVERWRITE'
  541. return owstr in os.environ and os.environ[owstr] != '0'
  542. # check GRASS_VERBOSE
  543. def verbosity():
  544. """!Return the verbosity level selected by GRASS_VERBOSE"""
  545. vbstr = os.getenv('GRASS_VERBOSE')
  546. if vbstr:
  547. return int(vbstr)
  548. else:
  549. return 0
  550. ## various utilities, not specific to GRASS
  551. # basename inc. extension stripping
  552. def basename(path, ext = None):
  553. """!Remove leading directory components and an optional extension
  554. from the specified path
  555. @param path path
  556. @param ext extension
  557. """
  558. name = os.path.basename(path)
  559. if not ext:
  560. return name
  561. fs = name.rsplit('.', 1)
  562. if len(fs) > 1 and fs[1].lower() == ext:
  563. name = fs[0]
  564. return name
  565. # find a program (replacement for "which")
  566. def find_program(pgm, args = []):
  567. """!Attempt to run a program, with optional arguments. Return False
  568. if the attempt failed due to a missing executable, True otherwise
  569. @param pgm program name
  570. @param args list of arguments
  571. """
  572. nuldev = file(os.devnull, 'w+')
  573. try:
  574. call([pgm] + args, stdin = nuldev, stdout = nuldev, stderr = nuldev)
  575. found = True
  576. except:
  577. found = False
  578. nuldev.close()
  579. return found
  580. # try to remove a file, without complaints
  581. def try_remove(path):
  582. """!Attempt to remove a file; no exception is generated if the
  583. attempt fails.
  584. @param path path
  585. """
  586. try:
  587. os.remove(path)
  588. except:
  589. pass
  590. # try to remove a directory, without complaints
  591. def try_rmdir(path):
  592. """!Attempt to remove a directory; no exception is generated if the
  593. attempt fails.
  594. @param path path
  595. """
  596. try:
  597. os.rmdir(path)
  598. except:
  599. pass
  600. def float_or_dms(s):
  601. """!Convert DMS to float.
  602. @param s DMS value
  603. @return float value
  604. """
  605. return sum(float(x) / 60 ** n for (n, x) in enumerate(s.split(':')))
  606. def command_info(cmd):
  607. """!Returns 'help' information for any command as dictionary with entries
  608. for description, keywords, usage, flags, and parameters"""
  609. cmdinfo = {}
  610. s = start_command(cmd, 'help', stdout = subprocess.PIPE, stderr = subprocess.PIPE)
  611. out, err = s.communicate()
  612. # Parameters
  613. first, params = err.split('Parameters:')
  614. paramlines = params.splitlines()
  615. dict = {}
  616. for line in paramlines:
  617. line = line.strip()
  618. if line == '': continue
  619. param = line.split(' ',1)[0].strip()
  620. pval = line.split(' ',1)[1].strip()
  621. dict[param] = pval
  622. cmdinfo['parameters'] = dict
  623. # Flags
  624. first, flags = first.split('Flags:')
  625. flaglines = flags.splitlines()
  626. dict = {}
  627. for line in flaglines:
  628. line = line.strip()
  629. if line == '': continue
  630. flag = line.split(' ',1)[0].strip()
  631. fval = line.split(' ',1)[1].strip()
  632. dict[flag] = fval
  633. cmdinfo['flags'] = dict
  634. # Usage
  635. first, usage = first.split('Usage:')
  636. usagelines = usage.splitlines()
  637. list = []
  638. for line in usagelines:
  639. line = line.strip()+' '
  640. if line == '': continue
  641. list.append(line)
  642. cmdinfo['usage'] = ''.join(list).strip()
  643. # Keywords
  644. first, keywords = first.split('Keywords:')
  645. list = []
  646. list = keywords.strip().split(',')
  647. cmdinfo['keywords'] = list
  648. #Description
  649. first, desc = first.split('Description:')
  650. desclines = desc.splitlines()
  651. for line in desclines:
  652. line = line.strip()+' '
  653. cmdinfo['description'] = ''.join(desclines).strip()
  654. return cmdinfo