core.py 22 KB

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