grass.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. #!/usr/bin/env python
  2. #############################################################################
  3. #
  4. # MODULE: GRASS initialization script
  5. # AUTHOR(S): Original author unknown - probably CERL
  6. # Andreas Lange <andreas.lange rhein-main.de>
  7. # Huidae Cho <grass4u gmail.com>
  8. # Justin Hickey <jhickey hpcc.nectec.or.th>
  9. # Markus Neteler <neteler osgeo.org>
  10. # Hamish Bowman <hamish_b yahoo.com>
  11. #
  12. # GRASS 7: converted to Python (based on init.sh shell
  13. # script from GRASS 6) by Glynn Clements
  14. # Martin Landa <landa.martin gmail.com>
  15. # Luca Delucchi <lucadeluge gmail.com>
  16. # PURPOSE: Sets up environment variables, parses any remaining
  17. # command line options for setting the GISDBASE, LOCATION,
  18. # and/or MAPSET. Finally it starts GRASS with the appropriate
  19. # user interface and cleans up after it is finished.
  20. # COPYRIGHT: (C) 2000-2014 by the GRASS Development Team
  21. #
  22. # This program is free software under the GNU General
  23. # Public License (>=v2). Read the file COPYING that
  24. # comes with GRASS for details.
  25. #
  26. #############################################################################
  27. import sys
  28. import os
  29. import atexit
  30. import string
  31. import subprocess
  32. import re
  33. import platform
  34. import tempfile
  35. # Variables substituted during build process
  36. if 'GISBASE' in os.environ:
  37. gisbase = os.environ['GISBASE']
  38. else:
  39. gisbase = "@GISBASE@"
  40. cmd_name = "@START_UP@"
  41. grass_version = "@GRASS_VERSION_NUMBER@"
  42. ld_library_path_var = '@LD_LIBRARY_PATH_VAR@'
  43. if 'GRASS_PROJSHARE' in os.environ:
  44. config_projshare = os.environ['GRASS_PROJSHARE']
  45. else:
  46. config_projshare = "@CONFIG_PROJSHARE@"
  47. # configuration directory
  48. grass_env_file = None # see check_shell()
  49. if sys.platform == 'win32':
  50. grass_config_dirname = "GRASS7"
  51. grass_config_dir = os.path.join(os.getenv('APPDATA'), grass_config_dirname)
  52. else:
  53. grass_config_dirname = ".grass7"
  54. grass_config_dir = os.path.join(os.getenv('HOME'), grass_config_dirname)
  55. gisbase = os.path.normpath(gisbase)
  56. # i18N
  57. import gettext
  58. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  59. tmpdir = None
  60. lockfile = None
  61. remove_lockfile = True
  62. location = None
  63. create_new = None
  64. grass_gui = None
  65. exit_grass = None
  66. def warning(text):
  67. sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
  68. def try_remove(path):
  69. try:
  70. os.remove(path)
  71. except:
  72. pass
  73. def try_rmdir(path):
  74. try:
  75. os.rmdir(path)
  76. except:
  77. pass
  78. def clean_env():
  79. env_curr = read_gisrc()
  80. env_new = {}
  81. for k,v in env_curr.iteritems():
  82. if 'MONITOR' not in k:
  83. env_new[k] = v
  84. write_gisrc(env_new)
  85. def cleanup_dir(path):
  86. if not path:
  87. return
  88. for root, dirs, files in os.walk(path, topdown=False):
  89. for name in files:
  90. try_remove(os.path.join(root, name))
  91. for name in dirs:
  92. try_rmdir(os.path.join(root, name))
  93. def cleanup():
  94. tmpdir, lockfile, remove_lockfile
  95. # all exits after setting up tmp dirs (system/location) should
  96. # also tidy it up
  97. cleanup_dir(tmpdir)
  98. try_rmdir(tmpdir)
  99. if location:
  100. tmpdir_loc = os.path.join(location, ".tmp")
  101. cleanup_dir(tmpdir_loc)
  102. try_rmdir(tmpdir_loc)
  103. # remove lock-file if requested
  104. if lockfile and remove_lockfile:
  105. try_remove(lockfile)
  106. def fatal(msg):
  107. sys.stderr.write("%s: " % _('ERROR') + msg + os.linesep)
  108. sys.exit(_("Exiting..."))
  109. def message(msg):
  110. sys.stderr.write(msg + "\n")
  111. sys.stderr.flush()
  112. def readfile(path):
  113. f = open(path, 'r')
  114. s = f.read()
  115. f.close()
  116. return s
  117. def writefile(path, s):
  118. f = open(path, 'w')
  119. f.write(s)
  120. f.close()
  121. def call(cmd, **kwargs):
  122. if windows:
  123. kwargs['shell'] = True
  124. return subprocess.call(cmd, **kwargs)
  125. def Popen(cmd, **kwargs):
  126. if windows:
  127. kwargs['shell'] = True
  128. return subprocess.Popen(cmd, **kwargs)
  129. def gfile(*args):
  130. return os.path.join(gisbase, *args)
  131. help_text = r"""GRASS GIS %s
  132. Geographic Resources Analysis Support System (GRASS GIS).
  133. %s:
  134. $CMD_NAME [-h | -help | --help] [-v | --version] [-c | -c geofile | -c EPSG:code[:datum_trans]]
  135. [-e] [-text | -gui] [--config param]
  136. [[[<GISDBASE>/]<LOCATION_NAME>/]<MAPSET>]
  137. %s:
  138. -h or -help or --help %s
  139. -v or --version %s
  140. -c %s
  141. -e %s
  142. -text %s
  143. %s
  144. -gtext %s
  145. %s
  146. -gui %s
  147. %s
  148. --config %s
  149. %s
  150. %s:
  151. GISDBASE %s
  152. LOCATION_NAME %s
  153. MAPSET %s
  154. GISDBASE/LOCATION_NAME/MAPSET %s
  155. %s:
  156. GRASS_GUI %s
  157. GRASS_HTML_BROWSER %s
  158. GRASS_ADDON_PATH %s
  159. GRASS_ADDON_BASE %s
  160. GRASS_BATCH_JOB %s
  161. GRASS_PYTHON %s
  162. """ % (grass_version,
  163. _("Usage"),
  164. _("Flags"),
  165. _("print this help message"),
  166. _("show version information and exit"),
  167. _("create given database, location or mapset if it doesn't exist"),
  168. _("exit after creation of location or mapset. Only with -c flag"),
  169. _("use text based interface (skip welcome screen)"),
  170. _("and set as default"),
  171. _("use text based interface (show welcome screen)"),
  172. _("and set as default"),
  173. _("use $DEFAULT_GUI graphical user interface"),
  174. _("and set as default"),
  175. _("print GRASS configuration parameters"),
  176. _("options: arch,build,compiler,path,revision"),
  177. _("Parameters"),
  178. _("initial database (path to GIS data)"),
  179. _("initial location"),
  180. _("initial mapset"),
  181. _("fully qualified initial mapset directory"),
  182. _("Environment variables relevant for startup"),
  183. _("select GUI (text, gui)"),
  184. _("set html web browser for help pages"),
  185. _("set additional path(s) to local GRASS modules or user scripts"),
  186. _("set additional GISBASE for locally installed GRASS Addons"),
  187. _("shell script to be processed as batch job"),
  188. _("set python shell name to override 'python'"))
  189. def help_message():
  190. t = string.Template(help_text)
  191. s = t.substitute(CMD_NAME=cmd_name, DEFAULT_GUI=default_gui)
  192. sys.stderr.write(s)
  193. def create_tmp():
  194. global tmpdir
  195. ## use $TMPDIR if it exists, then $TEMP, otherwise /tmp
  196. tmp = os.getenv('TMPDIR')
  197. if not tmp:
  198. tmp = os.getenv('TEMP')
  199. if not tmp:
  200. tmp = os.getenv('TMP')
  201. if not tmp:
  202. tmp = tempfile.gettempdir()
  203. if tmp:
  204. tmpdir = os.path.join(tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
  205. 'lock': gis_lock})
  206. try:
  207. os.mkdir(tmpdir, 0700)
  208. except:
  209. tmp = None
  210. if not tmp:
  211. for ttmp in ("/tmp", "/var/tmp", "/usr/tmp"):
  212. tmp = ttmp
  213. tmpdir = os.path.join(tmp, "grass7-%(user)s-%(lock)s" % {
  214. 'user': user, 'lock': gis_lock})
  215. try:
  216. os.mkdir(tmpdir, 0700)
  217. except:
  218. tmp = None
  219. if tmp:
  220. break
  221. if not tmp:
  222. fatal(_("Unable to create temporary directory <grass7-%(user)s-" \
  223. "%(lock)s>! Exiting.") % {'user': user, 'lock': gis_lock})
  224. def create_gisrc():
  225. global gisrc, gisrcrc
  226. # Set the session grassrc file
  227. gisrc = os.path.join(tmpdir, "gisrc")
  228. os.environ['GISRC'] = gisrc
  229. # remove invalid GISRC file to avoid disturbing error messages:
  230. try:
  231. s = readfile(gisrcrc)
  232. if "UNKNOWN" in s:
  233. try_remove(gisrcrc)
  234. s = None
  235. except:
  236. s = None
  237. # Copy the global grassrc file to the session grassrc file
  238. if s:
  239. writefile(gisrc, s)
  240. def read_gisrc():
  241. kv = {}
  242. try:
  243. f = open(gisrc, 'r')
  244. except IOError:
  245. return kv
  246. for line in f:
  247. k, v = line.split(':', 1)
  248. kv[k.strip()] = v.strip()
  249. f.close()
  250. return kv
  251. def read_env_file(path):
  252. kv = {}
  253. f = open(path, 'r')
  254. for line in f:
  255. k, v = line.split(':', 1)
  256. kv[k.strip()] = v.strip()
  257. f.close()
  258. return kv
  259. def write_gisrc(kv):
  260. f = open(gisrc, 'w')
  261. for k, v in kv.iteritems():
  262. f.write("%s: %s\n" % (k, v))
  263. f.close()
  264. def read_gui():
  265. global grass_gui
  266. # At this point the GRASS user interface variable has been set from the
  267. # command line, been set from an external environment variable, or is
  268. # not set. So we check if it is not set
  269. if not grass_gui:
  270. # Check for a reference to the GRASS user interface in the grassrc file
  271. if os.access(gisrc, os.R_OK):
  272. kv = read_gisrc()
  273. if 'GRASS_GUI' in os.environ:
  274. grass_gui = os.environ['GRASS_GUI']
  275. elif 'GUI' in kv:
  276. grass_gui = kv['GUI']
  277. elif 'GRASS_GUI' in kv:
  278. # For backward compatibility (GRASS_GUI renamed to GUI)
  279. grass_gui = kv['GRASS_GUI']
  280. else:
  281. # Set the GRASS user interface to the default if needed
  282. grass_gui = default_gui
  283. if not grass_gui:
  284. grass_gui = default_gui
  285. if grass_gui == 'gui':
  286. grass_gui = default_gui
  287. # FIXME oldtcltk, gis.m, d.m no longer exist
  288. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  289. warning(_("GUI <%s> not supported in this version") % grass_gui)
  290. grass_gui = default_gui
  291. def path_prepend(dir, var):
  292. path = os.getenv(var)
  293. if path:
  294. path = dir + os.pathsep + path
  295. else:
  296. path = dir
  297. os.environ[var] = path
  298. def path_append(dir, var):
  299. path = os.getenv(var)
  300. if path:
  301. path = path + os.pathsep + dir
  302. else:
  303. path = dir
  304. os.environ[var] = path
  305. def set_paths():
  306. # addons (path)
  307. addon_path = os.getenv('GRASS_ADDON_PATH')
  308. if addon_path:
  309. for path in addon_path.split(os.pathsep):
  310. path_prepend(addon_path, 'PATH')
  311. # addons (base)
  312. addon_base = os.getenv('GRASS_ADDON_BASE')
  313. if not addon_base:
  314. addon_base = os.path.join(grass_config_dir, 'addons')
  315. os.environ['GRASS_ADDON_BASE'] = addon_base
  316. if not windows:
  317. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  318. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  319. # standard installation
  320. if not windows:
  321. path_prepend(gfile('scripts'), 'PATH')
  322. path_prepend(gfile('bin'), 'PATH')
  323. # Set PYTHONPATH to find GRASS Python modules
  324. if os.path.exists(gfile('gui', 'wxpython')):
  325. path_prepend(gfile('gui', 'wxpython'), 'PYTHONPATH')
  326. if os.path.exists(gfile('etc', 'python')):
  327. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  328. # set path for the GRASS man pages
  329. grass_man_path = os.path.join(gisbase, 'docs', 'man')
  330. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  331. man_path = os.getenv('MANPATH')
  332. sys_man_path = None
  333. if man_path:
  334. path_prepend(addons_man_path, 'MANPATH')
  335. path_prepend(grass_man_path, 'MANPATH')
  336. else:
  337. try:
  338. nul = open(os.devnull, 'w')
  339. p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
  340. nul.close()
  341. s = p.stdout.read()
  342. p.wait()
  343. sys_man_path = s.strip()
  344. except:
  345. pass
  346. if sys_man_path:
  347. os.environ['MANPATH'] = sys_man_path
  348. path_prepend(addons_man_path, 'MANPATH')
  349. path_prepend(grass_man_path, 'MANPATH')
  350. else:
  351. os.environ['MANPATH'] = addons_man_path
  352. path_prepend(grass_man_path, 'MANPATH')
  353. def find_exe(pgm):
  354. for dir in os.getenv('PATH').split(os.pathsep):
  355. path = os.path.join(dir, pgm)
  356. if os.access(path, os.X_OK):
  357. return path
  358. return None
  359. def set_defaults():
  360. # GRASS_PAGER
  361. if not os.getenv('GRASS_PAGER'):
  362. if find_exe("more"):
  363. pager = "more"
  364. elif find_exe("less"):
  365. pager = "less"
  366. elif windows:
  367. pager = "more"
  368. else:
  369. pager = "cat"
  370. os.environ['GRASS_PAGER'] = pager
  371. # GRASS_PYTHON
  372. if not os.getenv('GRASS_PYTHON'):
  373. if windows:
  374. os.environ['GRASS_PYTHON'] = "python.exe"
  375. else:
  376. os.environ['GRASS_PYTHON'] = "python"
  377. # GRASS_GNUPLOT
  378. if not os.getenv('GRASS_GNUPLOT'):
  379. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  380. # GRASS_PROJSHARE
  381. if not os.getenv('GRASS_PROJSHARE'):
  382. os.environ['GRASS_PROJSHARE'] = config_projshare
  383. def set_browser():
  384. # GRASS_HTML_BROWSER
  385. browser = os.getenv('GRASS_HTML_BROWSER')
  386. if not browser:
  387. if macosx:
  388. # OSX doesn't execute browsers from the shell PATH - route thru a
  389. # script
  390. browser = gfile('etc', "html_browser_mac.sh")
  391. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  392. if windows or cygwin:
  393. # MinGW startup moved to into init.bat
  394. browser = "explorer"
  395. else:
  396. # the usual suspects
  397. browsers = ["xdg-open", "htmlview", "konqueror", "mozilla",
  398. "mozilla-firefox", "firefox", "iceweasel", "opera",
  399. "netscape", "dillo", "lynx", "links", "w3c"]
  400. for b in browsers:
  401. if find_exe(b):
  402. browser = b
  403. break
  404. elif macosx:
  405. # OSX doesn't execute browsers from the shell PATH - route thru a
  406. # script
  407. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  408. browser = gfile('etc', "html_browser_mac.sh")
  409. if not browser:
  410. warning(_("Searched for a web browser, but none found"))
  411. # even so we set konqueror to make lib/gis/parser.c happy:
  412. browser = "konqueror"
  413. os.environ['GRASS_HTML_BROWSER'] = browser
  414. def grass_intro():
  415. intro = _(r"""
  416. WELCOME TO GRASS %s
  417. 1) Have at your side all available GRASS GIS tutorials
  418. 2) When working on your location, the following materials
  419. are extremely useful:
  420. - A topographic map of your area
  421. - Current catalog of available computer maps
  422. 3) Check the GRASS GIS web pages for supporting mailing lists and more:
  423. http://grass.osgeo.org
  424. """) % grass_version
  425. sys.stderr.write(intro)
  426. sys.stderr.write("\n")
  427. sys.stderr.write(_("Hit RETURN to continue"))
  428. sys.stdin.readline()
  429. # for convenience, define pwd as GISDBASE:
  430. s = r"""GISDBASE: %s
  431. LOCATION_NAME: <UNKNOWN>
  432. MAPSET: <UNKNOWN>
  433. """ % os.getcwd()
  434. writefile(gisrc, s)
  435. def check_gui():
  436. global grass_gui, wxpython_base
  437. # Check if we are running X windows by checking the DISPLAY variable
  438. if os.getenv('DISPLAY') or windows or macosx:
  439. # Check if python is working properly
  440. if grass_gui in ('wxpython', 'gtext'):
  441. nul = open(os.devnull, 'w')
  442. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  443. stdout=nul, stderr=nul)
  444. nul.close()
  445. p.stdin.write("variable=True")
  446. p.stdin.close()
  447. p.wait()
  448. if p.returncode == 0:
  449. # Set the wxpython base directory
  450. wxpython_base = gfile("gui", "wxpython")
  451. else:
  452. # Python was not found - switch to text interface mode
  453. warning(_("The python command does not work as expected!\n"
  454. "Please check your GRASS_PYTHON environment variable.\n"
  455. "Use the -help option for details.\n"
  456. "Switching to text based interface mode.\n\n"
  457. "Hit RETURN to continue.\n"))
  458. sys.stdin.readline()
  459. grass_gui = 'text'
  460. else:
  461. # Display a message if a graphical interface was expected
  462. if grass_gui != 'text':
  463. # Set the interface mode to text
  464. warning(_("It appears that the X Windows system is not active.\n"
  465. "A graphical based user interface is not supported.\n"
  466. "Switching to text based interface mode.\n\n"
  467. "Hit RETURN to continue"""))
  468. sys.stdin.readline()
  469. grass_gui = 'text'
  470. # Save the user interface variable in the grassrc file - choose a temporary
  471. # file name that should not match another file
  472. if os.access(gisrc, os.F_OK):
  473. kv = read_gisrc()
  474. kv['GUI'] = grass_gui
  475. write_gisrc(kv)
  476. def non_interactive(arg, geofile=None):
  477. global gisdbase, location_name, mapset, location
  478. # Try non-interactive startup
  479. l = None
  480. if arg == '-':
  481. if location:
  482. l = location
  483. else:
  484. l = arg
  485. if l:
  486. if l == '.':
  487. l = os.getcwd()
  488. elif not os.path.isabs(l):
  489. l = os.path.abspath(l)
  490. l, mapset = os.path.split(l)
  491. if not mapset:
  492. l, mapset = os.path.split(l)
  493. l, location_name = os.path.split(l)
  494. gisdbase = l
  495. if gisdbase and location_name and mapset:
  496. location = os.path.join(gisdbase, location_name, mapset)
  497. # check if 'location' is a valid GRASS location/mapset
  498. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  499. if not create_new:
  500. # 'location' is not valid, check if 'location_name' is
  501. # a valid GRASS location
  502. if not os.path.exists(os.path.join(gisdbase, location_name)):
  503. fatal(_("Location <%s> doesn't exist") % os.path.join(gisdbase, location_name))
  504. elif 'PERMANENT' not in os.listdir(os.path.join(gisdbase, location_name)) or \
  505. not os.path.isdir(os.path.join(gisdbase, location_name, 'PERMANENT')) or \
  506. not os.path.isfile((os.path.join(gisdbase, location_name, 'PERMANENT',
  507. 'DEFAULT_WIND'))):
  508. fatal(_("ERROR: <%s> is not a valid GRASS location") % \
  509. os.path.join(gisdbase, location_name))
  510. else:
  511. fatal(_("Mapset <%s> doesn't exist in GRASS location <%s>. "
  512. "A new mapset can be created by '-c' switch.") % (mapset, location_name))
  513. else:
  514. # 'location' is not valid, the user wants to create
  515. # mapset on the fly
  516. if not os.access(os.path.join(gisdbase, location_name,
  517. "PERMANENT",
  518. "DEFAULT_WIND"), os.F_OK):
  519. # 'location_name' is not a valid GRASS location,
  520. # create new location and 'PERMANENT' mapset
  521. gisdbase = os.path.join(gisdbase, location_name)
  522. location_name = mapset
  523. mapset = "PERMANENT"
  524. if os.access(os.path.join(os.path.join(gisdbase,
  525. location_name,
  526. "PERMANENT",
  527. "DEFAULT_WIND")),
  528. os.F_OK):
  529. fatal(_("Failed to create new location. "
  530. "The location <%s> already exists." % location_name))
  531. if gfile('etc', 'python') not in sys.path:
  532. sys.path.append(gfile('etc', 'python'))
  533. from grass.script import core as grass
  534. try:
  535. if geofile and geofile.upper().find('EPSG:') > -1:
  536. # create location using EPSG code
  537. epsg = geofile.split(':', 1)[1]
  538. if ':' in epsg:
  539. epsg, datum_trans = epsg.split(':', 1)
  540. else:
  541. datum_trans = None
  542. grass.create_location(gisdbase, location_name,
  543. epsg=epsg, datum_trans=datum_trans)
  544. else:
  545. # create location using georeferenced file
  546. grass.create_location(gisdbase, location_name,
  547. filename=geofile)
  548. except grass.ScriptError as e:
  549. fatal(e.value.strip('"').strip("'").replace('\\n',
  550. os.linesep))
  551. else:
  552. # 'location_name' is a valid GRASS location,
  553. # create new mapset
  554. os.mkdir(location)
  555. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  556. s = readfile(os.path.join(gisdbase, location_name,
  557. "PERMANENT", "DEFAULT_WIND"))
  558. writefile(os.path.join(location, "WIND"), s)
  559. message(_("Missing WIND file fixed"))
  560. if os.access(gisrc, os.R_OK):
  561. kv = read_gisrc()
  562. else:
  563. kv = {}
  564. kv['GISDBASE'] = gisdbase
  565. kv['LOCATION_NAME'] = location_name
  566. kv['MAPSET'] = mapset
  567. write_gisrc(kv)
  568. else:
  569. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  570. "Interactive startup needed."))
  571. def set_data():
  572. # User selects LOCATION and MAPSET if not set
  573. if not location:
  574. # Check for text interface
  575. if grass_gui == 'text':
  576. pass
  577. # Check for GUI
  578. elif grass_gui in ('gtext', 'wxpython'):
  579. gui_startup(grass_gui == 'gtext')
  580. else:
  581. # Shouldn't need this but you never know
  582. fatal(_("Invalid user interface specified - <%s>. "
  583. "Use the --help option to see valid interface names.") % grass_gui)
  584. def gui_startup(wscreen_only = False):
  585. if grass_gui in ('wxpython', 'gtext'):
  586. ret = call([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "gis_set.py")])
  587. if ret == 0:
  588. pass
  589. elif ret == 1:
  590. # The startup script printed an error message so wait
  591. # for user to read it
  592. message(_("Error in GUI startup. If necessary, please "
  593. "report this error to the GRASS developers.\n"
  594. "Switching to text mode now.\n\n"
  595. "Hit RETURN to continue..."))
  596. sys.stdin.readline()
  597. os.execlp(cmd_name, "-text")
  598. sys.exit(1)
  599. elif ret == 2:
  600. # User wants to exit from GRASS
  601. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  602. sys.exit(0)
  603. else:
  604. fatal(_("Invalid return code from GUI startup script.\n"
  605. "Please advise GRASS developers of this error."))
  606. def load_gisrc():
  607. global gisdbase, location_name, mapset, location
  608. kv = read_gisrc()
  609. gisdbase = kv.get('GISDBASE')
  610. location_name = kv.get('LOCATION_NAME')
  611. mapset = kv.get('MAPSET')
  612. if not gisdbase or not location_name or not mapset:
  613. fatal(_("Error reading data path information from g.gisenv.\n"
  614. "GISDBASE=%(gisbase)s\n"
  615. "LOCATION_NAME=%(location)s\n"
  616. "MAPSET=%(mapset)s\n\n"
  617. "Check the <%s(file)> file." % \
  618. {'gisbase': gisdbase, 'location': location_name,
  619. 'mapset': mapset, 'file': gisrcrc}))
  620. location = os.path.join(gisdbase, location_name, mapset)
  621. # load environmental variables from grass_env_file
  622. def load_env():
  623. if not os.access(grass_env_file, os.R_OK):
  624. return
  625. for line in readfile(grass_env_file).split(os.linesep):
  626. try:
  627. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  628. except:
  629. continue
  630. evalue = os.getenv(k)
  631. if evalue:
  632. if k == 'GRASS_ADDON_PATH':
  633. os.environ[k] = evalue + os.pathsep + v
  634. else:
  635. warning(_("Environmental variable '%s' already set, ignoring value '%s'") % \
  636. (k, v))
  637. else:
  638. os.environ[k] = v
  639. # Allow for mixed ISIS-GRASS Environment
  640. if os.getenv('ISISROOT'):
  641. isis = os.getenv('ISISROOT')
  642. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  643. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  644. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  645. #os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  646. libpath = os.getenv('LD_LIBRARY_PATH', '')
  647. isislibpath = os.getenv('ISIS_LIB')
  648. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  649. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  650. def set_language():
  651. # This function is used to override system default language and locale
  652. # Such override can be requested only from wxGUI
  653. # An override if user has provided correct environmental variables as
  654. # LC_MESSAGES or LANG is not necessary.
  655. # Unfortunately currently a working solution for Windows is lacking
  656. # thus it always on Vista and XP will print an error.
  657. # See discussion for Windows not following its own documentation and
  658. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  659. import locale
  660. language = 'None' # Such string sometimes is present in wx file
  661. # Override value is stored in wxGUI preferences file.
  662. # As it's the only thing required, we'll just grep it out.
  663. try:
  664. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  665. except:
  666. # Even if there is no override, we still need to set locale.
  667. pass
  668. else:
  669. for line in fd:
  670. if re.search('^language', line):
  671. line = line.rstrip('%s' % os.linesep)
  672. language = ''.join(line.split(';')[-1:])
  673. break
  674. fd.close()
  675. if language == 'None' or language == '' or not language:
  676. # Language override is disabled (system language specified)
  677. # As by default program runs with C locale, but users expect to
  678. # have their default locale, we'll just set default locale
  679. locale.setlocale(locale.LC_ALL, '')
  680. if windows and os.getenv('LANG') is None:
  681. language, encoding = locale.getdefaultlocale()
  682. os.environ['LANG'] = language
  683. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), codeset=encoding)
  684. else:
  685. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  686. return
  687. warning("A language override has been requested. Trying to switch GRASS into '%s'..." % language)
  688. # Even if setting locale will fail, let's set LANG in a hope,
  689. # that UI will use it GRASS texts will be in selected language,
  690. # system messages (i.e. OK, Cancel etc.) - in system default
  691. # language
  692. os.environ['LANGUAGE'] = language
  693. os.environ['LANG'] = language
  694. try:
  695. locale.setlocale(locale.LC_ALL, language)
  696. except locale.Error as e:
  697. try:
  698. # Locale lang.encoding might be missing. Let's try
  699. # UTF-8 encoding before giving up as on Linux systems
  700. # lang.UTF-8 locales are more common than legacy
  701. # ISO-8859 ones.
  702. language = locale.normalize('%s.UTF-8' % (language))
  703. locale.setlocale(locale.LC_ALL, language)
  704. except locale.Error as e:
  705. # The last attempt...
  706. try:
  707. language = locale.normalize('%s.%s' % (language, locale.getpreferredencoding()))
  708. locale.setlocale(locale.LC_ALL, language)
  709. except locale.Error as e:
  710. # If we got so far, attempts to set up language and locale have failed
  711. # on this system
  712. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  713. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  714. return
  715. # Set up environment for subprocesses
  716. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  717. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  718. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  719. os.environ[lc] = language
  720. # Some code in GRASS might not like other decimal separators than .
  721. # Other potential sources for problems are: LC_TIME LC_CTYPE
  722. locale.setlocale(locale.LC_NUMERIC, 'C')
  723. os.environ['LC_NUMERIC'] = 'C'
  724. if os.getenv('LC_ALL'):
  725. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  726. # From now on enforce the new language
  727. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  728. def check_lock():
  729. global lockfile
  730. if not os.path.exists(location):
  731. fatal(_("Path '%s' doesn't exist") % location)
  732. # Check for concurrent use
  733. lockfile = os.path.join(location, ".gislock")
  734. ret = call([gfile("etc", "lock"), lockfile, "%d" % os.getpid()])
  735. if ret == 0:
  736. msg = None
  737. elif ret == 2:
  738. msg = _("%(user)s is currently running GRASS in selected mapset (" \
  739. "file %(file)s found). Concurrent use not allowed." % {
  740. 'user': user, 'file': lockfile})
  741. else:
  742. msg = _("Unable to properly access '%s'.\n"
  743. "Please notify system personel.") % lockfile
  744. if msg:
  745. if grass_gui == "wxpython":
  746. call([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "gis_set_error.py"), msg])
  747. else:
  748. global remove_lockfile
  749. remove_lockfile = False
  750. fatal(msg)
  751. def make_fontcap():
  752. fc = os.getenv('GRASS_FONT_CAP')
  753. if fc and not os.access(fc, os.R_OK):
  754. message(_("Building user fontcap..."))
  755. call(["g.mkfontcap"])
  756. def check_shell():
  757. global sh, shellname, grass_env_file
  758. # cygwin has many problems with the shell setup
  759. # below, so i hardcoded everything here.
  760. if sys.platform == 'cygwin':
  761. sh = "cygwin"
  762. shellname = "GNU Bash (Cygwin)"
  763. os.environ['SHELL'] = "/usr/bin/bash.exe"
  764. os.environ['OSTYPE'] = "cygwin"
  765. else:
  766. sh = os.path.basename(os.getenv('SHELL'))
  767. if windows and sh:
  768. sh = os.path.splitext(sh)[0]
  769. if sh == "ksh":
  770. shellname = "Korn Shell"
  771. elif sh == "csh":
  772. shellname = "C Shell"
  773. elif sh == "tcsh":
  774. shellname = "TC Shell"
  775. elif sh == "bash":
  776. shellname = "Bash Shell"
  777. elif sh == "sh":
  778. shellname = "Bourne Shell"
  779. elif sh == "zsh":
  780. shellname = "Z Shell"
  781. elif sh == "cmd":
  782. shellname = "Command Shell"
  783. else:
  784. shellname = "shell"
  785. if sh in ['csh', 'tcsh']:
  786. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  787. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  788. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  789. elif sh == 'zsh':
  790. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  791. elif sh == 'cmd':
  792. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  793. else:
  794. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  795. warning(_("Unsupported shell <%(sh)s>: %(env)s") % {'sh': sh,
  796. 'env': grass_env_file})
  797. # check for SHELL
  798. if not os.getenv('SHELL'):
  799. fatal(_("The SHELL variable is not set"))
  800. def check_batch_job():
  801. global batch_job
  802. # hack to process batch jobs:
  803. batch_job = os.getenv('GRASS_BATCH_JOB')
  804. if batch_job:
  805. # defined, but ...
  806. if not os.access(batch_job, os.F_OK):
  807. # wrong file
  808. fatal(_("Job file '%s' has been defined in "
  809. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  810. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  811. elif not os.access(batch_job, os.X_OK):
  812. # right file, but ...
  813. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  814. else:
  815. message(_("Executing '%s' ...") % batch_job)
  816. grass_gui = "text"
  817. shell = batch_job
  818. bj = Popen(shell, shell=True)
  819. bj.wait()
  820. message(_("Execution of '%s' finished.") % batch_job)
  821. def start_gui():
  822. # Start the chosen GUI but ignore text
  823. if grass_debug:
  824. message(_("GRASS GUI should be <%s>") % grass_gui)
  825. # Check for gui interface
  826. if grass_gui == "wxpython":
  827. Popen([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "wxgui.py")])
  828. def clear_screen():
  829. if windows:
  830. pass
  831. # TODO: uncomment when PDCurses works.
  832. # cls
  833. else:
  834. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug and not exit_grass:
  835. call(["tput", "clear"])
  836. def show_banner():
  837. sys.stderr.write(r"""
  838. __________ ___ __________ _______________
  839. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  840. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  841. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  842. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  843. """)
  844. def say_hello():
  845. sys.stderr.write(_("Welcome to GRASS %s") % grass_version)
  846. if grass_version.endswith('svn'):
  847. try:
  848. filerev = open(os.path.join(gisbase, 'etc', 'VERSIONNUMBER'))
  849. linerev = filerev.readline().rstrip('\n')
  850. filerev.close()
  851. revision = linerev.split(' ')[1]
  852. sys.stderr.write(' (' + revision + ')')
  853. except:
  854. pass
  855. def show_info():
  856. sys.stderr.write(
  857. r"""
  858. %-41shttp://grass.osgeo.org
  859. %-41s%s (%s)
  860. %-41sg.manual -i
  861. %-41sg.version -c
  862. """ % (_("GRASS homepage:"),
  863. _("This version running through:"),
  864. shellname, os.getenv('SHELL'),
  865. _("Help is available with the command:"),
  866. _("See the licence terms with:")))
  867. if grass_gui == 'wxpython':
  868. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  869. else:
  870. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  871. message("%-41sexit" % _("When ready to quit enter:"))
  872. message("")
  873. def csh_startup():
  874. global exit_val
  875. userhome = os.getenv('HOME') # save original home
  876. home = location
  877. os.environ['HOME'] = home
  878. cshrc = os.path.join(home, ".cshrc")
  879. tcshrc = os.path.join(home, ".tcshrc")
  880. try_remove(cshrc)
  881. try_remove(tcshrc)
  882. f = open(cshrc, 'w')
  883. f.write("set home = %s\n" % userhome)
  884. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  885. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  886. ".history"))
  887. f.write("set prompt = '\\\n")
  888. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  889. f.write("GRASS %s > '\n" % grass_version)
  890. f.write("set BOGUS=``;unset BOGUS\n")
  891. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  892. if os.access(path, os.R_OK):
  893. f.write(readfile(path) + '\n')
  894. if os.access(grass_env_file, os.R_OK):
  895. f.write(readfile(grass_env_file) + '\n')
  896. mail_re = re.compile(r"^ *set *mail *= *")
  897. for filename in [".cshrc", ".tcshrc", ".login"]:
  898. path = os.path.join(userhome, filename)
  899. if os.access(path, os.R_OK):
  900. s = readfile(path)
  901. lines = s.splitlines()
  902. for l in lines:
  903. if mail_re.match(l):
  904. f.write(l)
  905. path = os.getenv('PATH').split(':')
  906. f.write("set path = ( %s ) \n" % ' '.join(path))
  907. f.close()
  908. writefile(tcshrc, readfile(cshrc))
  909. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  910. os.environ['HOME'] = userhome
  911. def bash_startup():
  912. global exit_val
  913. # save command history in mapset dir and remember more
  914. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  915. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  916. os.environ['HISTSIZE'] = "3000"
  917. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  918. # if so, must care be taken to explicity call .grass.bashrc et al for
  919. # non-interactive bash batch jobs?
  920. userhome = os.getenv('HOME') # save original home
  921. home = location # save .bashrc in $LOCATION
  922. os.environ['HOME'] = home
  923. bashrc = os.path.join(home, ".bashrc")
  924. try_remove(bashrc)
  925. f = open(bashrc, 'w')
  926. f.write("test -r ~/.alias && . ~/.alias\n")
  927. if os.getenv('ISISROOT'):
  928. f.write("PS1='ISIS-GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  929. else:
  930. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  931. f.write("""grass_prompt() {
  932. LOCATION="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  933. if test -d "$LOCATION/grid3/G3D_MASK" && test -f "$LOCATION/cell/MASK" ; then
  934. echo [%s]
  935. elif test -f "$LOCATION/cell/MASK" ; then
  936. echo [%s]
  937. elif test -d "$LOCATION/grid3/G3D_MASK" ; then
  938. echo [%s]
  939. fi
  940. }
  941. PROMPT_COMMAND=grass_prompt\n""" % (_("2D and 3D raster MASKs present"),
  942. _("Raster MASK present"),
  943. _("3D raster MASK present")))
  944. # read environmental variables
  945. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  946. if os.access(path, os.R_OK):
  947. f.write(readfile(path) + '\n')
  948. for env in os.environ.keys():
  949. if env.startswith('GRASS'):
  950. val = os.environ[env]
  951. if ' ' in val:
  952. val = '"%s"' % val
  953. f.write('export %s=%s\n' % (env, val))
  954. ### Replaced by code above (do not override already set up environment variables)
  955. ### if os.access(grass_env_file, os.R_OK):
  956. ### f.write(readfile(grass_env_file) + '\n')
  957. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  958. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  959. f.close()
  960. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  961. os.environ['HOME'] = userhome
  962. def default_startup():
  963. global exit_val
  964. if windows:
  965. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  966. # "$ETC/run" doesn't work at all???
  967. exit_val = subprocess.call([os.getenv('SHELL')])
  968. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  969. else:
  970. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  971. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  972. if exit_val != 0:
  973. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  974. def done_message():
  975. if batch_job and os.access(batch_job, os.X_OK):
  976. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  977. message(_("Goodbye from GRASS GIS"))
  978. sys.exit(exit_val)
  979. else:
  980. message(_("Done."))
  981. message("")
  982. message(_("Goodbye from GRASS GIS"))
  983. message("")
  984. def clean_temp():
  985. message(_("Cleaning up temporary files..."))
  986. nul = open(os.devnull, 'w')
  987. call([gfile("etc", "clean_temp")], stdout=nul, stderr=nul)
  988. nul.close()
  989. def grep(string,list):
  990. expr = re.compile(string)
  991. return [elem for elem in list if expr.match(elem)]
  992. def print_params():
  993. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  994. fileplat = open(plat)
  995. linesplat = fileplat.readlines()
  996. fileplat.close()
  997. params = sys.argv[2:]
  998. if not params:
  999. params = ['arch', 'build', 'compiler', 'path', 'revision']
  1000. for arg in params:
  1001. if arg == 'path':
  1002. sys.stdout.write("%s\n" % gisbase)
  1003. elif arg == 'arch':
  1004. val = grep('ARCH',linesplat)
  1005. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1006. elif arg == 'build':
  1007. build = os.path.join(gisbase,'include','grass','confparms.h')
  1008. filebuild = open(build)
  1009. val = filebuild.readline()
  1010. filebuild.close()
  1011. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1012. elif arg == 'compiler':
  1013. val = grep('CC',linesplat)
  1014. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1015. elif arg == 'revision':
  1016. rev = os.path.join(gisbase,'include','grass','gis.h')
  1017. filerev = open(rev)
  1018. linesrev = filerev.readlines()
  1019. val = grep('#define GIS_H_VERSION', linesrev)
  1020. filerev.close()
  1021. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1022. else:
  1023. message(_("Parameter <%s> not supported") % arg)
  1024. def get_username():
  1025. global user
  1026. if windows:
  1027. user = os.getenv('USERNAME')
  1028. if not user:
  1029. user = "user_name"
  1030. else:
  1031. user = os.getenv('USER')
  1032. if not user:
  1033. user = os.getenv('LOGNAME')
  1034. if not user:
  1035. try:
  1036. p = Popen(['whoami'], stdout = subprocess.PIPE)
  1037. s = p.stdout.read()
  1038. p.wait()
  1039. user = s.strip()
  1040. except:
  1041. pass
  1042. if not user:
  1043. user = "user_%d" % os.getuid()
  1044. def parse_cmdline():
  1045. global args, grass_gui, create_new, exit_grass
  1046. args = []
  1047. for i in sys.argv[1:]:
  1048. # Check if the user asked for the version
  1049. if i in ["-v", "--version"]:
  1050. message('\n' + readfile(gfile("etc", "license")))
  1051. sys.exit()
  1052. # Check if the user asked for help
  1053. elif i in ["help", "-h", "-help", "--help"]:
  1054. help_message()
  1055. sys.exit()
  1056. # Check if the -text flag was given
  1057. elif i in ["-text", "--text"]:
  1058. grass_gui = 'text'
  1059. # Check if the -gtext flag was given
  1060. elif i in ["-gtext", "--gtext"]:
  1061. grass_gui = 'gtext'
  1062. # Check if the -gui flag was given
  1063. elif i in ["-gui", "--gui"]:
  1064. grass_gui = default_gui
  1065. # Check if the -wxpython flag was given
  1066. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1067. grass_gui = 'wxpython'
  1068. # Check if the user wants to create a new mapset
  1069. elif i == "-c":
  1070. create_new = True
  1071. elif i == "-e":
  1072. exit_grass = True
  1073. elif i == "--config":
  1074. print_params()
  1075. sys.exit()
  1076. else:
  1077. args.append(i)
  1078. ### MAIN script starts here
  1079. # Get the system name
  1080. windows = sys.platform == 'win32'
  1081. cygwin = "cygwin" in sys.platform
  1082. macosx = "darwin" in sys.platform
  1083. ### commented-out: broken winGRASS
  1084. # if 'GISBASE' in os.environ:
  1085. # sys.exit(_("ERROR: GRASS GIS is already running "
  1086. # "(environmental variable GISBASE found)"))
  1087. # Set GISBASE
  1088. os.environ['GISBASE'] = gisbase
  1089. # set HOME
  1090. if windows and not os.getenv('HOME'):
  1091. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  1092. os.getenv('HOMEPATH'))
  1093. # set SHELL
  1094. if windows:
  1095. if os.getenv('GRASS_SH'):
  1096. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1097. if not os.getenv('SHELL'):
  1098. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1099. atexit.register(cleanup)
  1100. # Set default GUI
  1101. default_gui = "wxpython"
  1102. # the following is only meant to be an internal variable for debugging this
  1103. # script. use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly
  1104. grass_debug = os.getenv('GRASS_DEBUG')
  1105. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  1106. os.environ['GRASS_VERSION'] = grass_version
  1107. # Set the GIS_LOCK variable to current process id
  1108. gis_lock = str(os.getpid())
  1109. os.environ['GIS_LOCK'] = gis_lock
  1110. if not os.path.exists(grass_config_dir):
  1111. os.mkdir(grass_config_dir)
  1112. # Set the global grassrc file
  1113. batch_job = os.getenv('GRASS_BATCH_JOB')
  1114. if batch_job:
  1115. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  1116. if not os.access(gisrcrc, os.R_OK):
  1117. gisrcrc = os.path.join(grass_config_dir, "rc")
  1118. else:
  1119. gisrcrc = os.path.join(grass_config_dir, "rc")
  1120. # Set the username and working directory
  1121. get_username()
  1122. # Parse the command-line options
  1123. parse_cmdline()
  1124. if exit_grass and not create_new:
  1125. fatal(_("Flag -e required also flag -c"))
  1126. # Set language
  1127. # This has to be called before any _() function call!
  1128. # Subsequent functions are using _() calls and
  1129. # thus must be called only after Language has been set.
  1130. set_language()
  1131. # Create the temporary directory and session grassrc file
  1132. create_tmp()
  1133. # Create the session grassrc file
  1134. create_gisrc()
  1135. # Set shell (needs to be called before load_env())
  1136. check_shell()
  1137. # Load environmental variables from the file
  1138. load_env()
  1139. # Ensure GUI is set
  1140. read_gui()
  1141. # Set PATH, PYTHONPATH
  1142. set_paths()
  1143. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  1144. path_prepend(gfile("lib"), ld_library_path_var)
  1145. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1146. set_defaults()
  1147. # Set GRASS_HTML_BROWSER
  1148. set_browser()
  1149. #predefine monitor size for certain architectures
  1150. if os.getenv('HOSTTYPE') == 'arm':
  1151. # small monitor on ARM (iPAQ, zaurus... etc)
  1152. os.environ['GRASS_RENDER_HEIGHT'] = "320"
  1153. os.environ['GRASS_RENDER_WIDTH'] = "240"
  1154. # First time user - GISRC is defined in the GRASS script
  1155. if not os.access(gisrc, os.F_OK):
  1156. if grass_gui == 'text' and len(args) == 0:
  1157. fatal(_("Unable to start GRASS. You can:\n"
  1158. " - Launch GRASS with '-gui' switch (`grass70 -gui`)\n"
  1159. " - Create manually GISRC file (%s)\n"
  1160. " - Launch GRASS with path to "
  1161. "the location/mapset as an argument (`grass70 /path/to/location/mapset`)") % gisrcrc)
  1162. grass_intro()
  1163. else:
  1164. clean_temp()
  1165. if create_new:
  1166. message(_("Creating new GRASS GIS location/mapset..."))
  1167. else:
  1168. message(_("Starting GRASS GIS..."))
  1169. # Check that the GUI works
  1170. check_gui()
  1171. # Parsing argument to get LOCATION
  1172. if not args:
  1173. # Try interactive startup
  1174. location = None
  1175. else:
  1176. if create_new:
  1177. if len(args) > 1:
  1178. non_interactive(args[1], args[0])
  1179. else:
  1180. non_interactive(args[0])
  1181. else:
  1182. non_interactive(args[0])
  1183. # User selects LOCATION and MAPSET if not set
  1184. set_data()
  1185. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1186. load_gisrc()
  1187. # Check .gislock file
  1188. check_lock()
  1189. # build user fontcap if specified but not present
  1190. make_fontcap()
  1191. # predefine default driver if DB connection not defined
  1192. # is this really needed?? Modules should call this when/if required.
  1193. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1194. call(['db.connect', '-c', '--quiet'])
  1195. check_batch_job()
  1196. if not batch_job and not exit_grass:
  1197. start_gui()
  1198. clear_screen()
  1199. # Display the version and license info
  1200. if batch_job:
  1201. grass_gui = 'text'
  1202. clear_screen()
  1203. clean_temp()
  1204. try_remove(lockfile)
  1205. sys.exit(0)
  1206. elif exit_grass:
  1207. clean_temp()
  1208. try_remove(lockfile)
  1209. sys.exit(0)
  1210. else:
  1211. show_banner()
  1212. say_hello()
  1213. show_info()
  1214. if grass_gui == "wxpython":
  1215. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1216. if sh in ['csh', 'tcsh']:
  1217. csh_startup()
  1218. elif sh in ['bash', 'msh', 'cygwin']:
  1219. bash_startup()
  1220. else:
  1221. default_startup()
  1222. clear_screen()
  1223. clean_env()
  1224. clean_temp()
  1225. try_remove(lockfile)
  1226. # Save GISRC
  1227. s = readfile(gisrc)
  1228. writefile(gisrcrc, s)
  1229. cleanup()
  1230. # After this point no more grass modules may be called
  1231. done_message()