grass.py 48 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]
  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. # Add .py (Python) to list of executable extensions to search for
  354. # in MS-Windows PATH
  355. if windows:
  356. path_append('.PY', 'PATHEXT')
  357. def find_exe(pgm):
  358. for dir in os.getenv('PATH').split(os.pathsep):
  359. path = os.path.join(dir, pgm)
  360. if os.access(path, os.X_OK):
  361. return path
  362. return None
  363. def set_defaults():
  364. # GRASS_PAGER
  365. if not os.getenv('GRASS_PAGER'):
  366. if find_exe("more"):
  367. pager = "more"
  368. elif find_exe("less"):
  369. pager = "less"
  370. elif windows:
  371. pager = "more"
  372. else:
  373. pager = "cat"
  374. os.environ['GRASS_PAGER'] = pager
  375. # GRASS_PYTHON
  376. if not os.getenv('GRASS_PYTHON'):
  377. if windows:
  378. os.environ['GRASS_PYTHON'] = "python.exe"
  379. else:
  380. os.environ['GRASS_PYTHON'] = "python"
  381. # GRASS_GNUPLOT
  382. if not os.getenv('GRASS_GNUPLOT'):
  383. os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
  384. # GRASS_PROJSHARE
  385. if not os.getenv('GRASS_PROJSHARE'):
  386. os.environ['GRASS_PROJSHARE'] = config_projshare
  387. def set_browser():
  388. # GRASS_HTML_BROWSER
  389. browser = os.getenv('GRASS_HTML_BROWSER')
  390. if not browser:
  391. if macosx:
  392. # OSX doesn't execute browsers from the shell PATH - route thru a
  393. # script
  394. browser = gfile('etc', "html_browser_mac.sh")
  395. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
  396. if windows or cygwin:
  397. # MinGW startup moved to into init.bat
  398. browser = "explorer"
  399. else:
  400. # the usual suspects
  401. browsers = ["xdg-open", "htmlview", "konqueror", "mozilla",
  402. "mozilla-firefox", "firefox", "iceweasel", "opera",
  403. "netscape", "dillo", "lynx", "links", "w3c"]
  404. for b in browsers:
  405. if find_exe(b):
  406. browser = b
  407. break
  408. elif macosx:
  409. # OSX doesn't execute browsers from the shell PATH - route thru a
  410. # script
  411. os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
  412. browser = gfile('etc', "html_browser_mac.sh")
  413. if not browser:
  414. warning(_("Searched for a web browser, but none found"))
  415. # even so we set konqueror to make lib/gis/parser.c happy:
  416. browser = "konqueror"
  417. os.environ['GRASS_HTML_BROWSER'] = browser
  418. def grass_intro():
  419. intro = _(r"""
  420. WELCOME TO GRASS %s
  421. 1) Have at your side all available GRASS GIS tutorials
  422. 2) When working on your location, the following materials
  423. are extremely useful:
  424. - A topographic map of your area
  425. - Current catalog of available computer maps
  426. 3) Check the GRASS GIS web pages for supporting mailing lists and more:
  427. http://grass.osgeo.org
  428. """) % grass_version
  429. sys.stderr.write(intro)
  430. sys.stderr.write("\n")
  431. sys.stderr.write(_("Hit RETURN to continue"))
  432. sys.stdin.readline()
  433. # for convenience, define pwd as GISDBASE:
  434. s = r"""GISDBASE: %s
  435. LOCATION_NAME: <UNKNOWN>
  436. MAPSET: <UNKNOWN>
  437. """ % os.getcwd()
  438. writefile(gisrc, s)
  439. def check_gui():
  440. global grass_gui, wxpython_base
  441. # Check if we are running X windows by checking the DISPLAY variable
  442. if os.getenv('DISPLAY') or windows or macosx:
  443. # Check if python is working properly
  444. if grass_gui in ('wxpython', 'gtext'):
  445. nul = open(os.devnull, 'w')
  446. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  447. stdout=nul, stderr=nul)
  448. nul.close()
  449. p.stdin.write("variable=True")
  450. p.stdin.close()
  451. p.wait()
  452. if p.returncode == 0:
  453. # Set the wxpython base directory
  454. wxpython_base = gfile("gui", "wxpython")
  455. else:
  456. # Python was not found - switch to text interface mode
  457. warning(_("The python command does not work as expected!\n"
  458. "Please check your GRASS_PYTHON environment variable.\n"
  459. "Use the -help option for details.\n"
  460. "Switching to text based interface mode.\n\n"
  461. "Hit RETURN to continue.\n"))
  462. sys.stdin.readline()
  463. grass_gui = 'text'
  464. else:
  465. # Display a message if a graphical interface was expected
  466. if grass_gui != 'text':
  467. # Set the interface mode to text
  468. warning(_("It appears that the X Windows system is not active.\n"
  469. "A graphical based user interface is not supported.\n"
  470. "Switching to text based interface mode.\n\n"
  471. "Hit RETURN to continue"""))
  472. sys.stdin.readline()
  473. grass_gui = 'text'
  474. # Save the user interface variable in the grassrc file - choose a temporary
  475. # file name that should not match another file
  476. if os.access(gisrc, os.F_OK):
  477. kv = read_gisrc()
  478. kv['GUI'] = grass_gui
  479. write_gisrc(kv)
  480. def non_interactive(arg, geofile=None):
  481. global gisdbase, location_name, mapset, location
  482. # Try non-interactive startup
  483. l = None
  484. if arg == '-':
  485. if location:
  486. l = location
  487. else:
  488. l = arg
  489. if l:
  490. if l == '.':
  491. l = os.getcwd()
  492. elif not os.path.isabs(l):
  493. l = os.path.abspath(l)
  494. l, mapset = os.path.split(l)
  495. if not mapset:
  496. l, mapset = os.path.split(l)
  497. l, location_name = os.path.split(l)
  498. gisdbase = l
  499. if gisdbase and location_name and mapset:
  500. location = os.path.join(gisdbase, location_name, mapset)
  501. # check if 'location' is a valid GRASS location/mapset
  502. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  503. if not create_new:
  504. # 'location' is not valid, check if 'location_name' is
  505. # a valid GRASS location
  506. if not os.path.exists(os.path.join(gisdbase, location_name)):
  507. fatal(_("Location <%s> doesn't exist") % os.path.join(gisdbase, location_name))
  508. elif 'PERMANENT' not in os.listdir(os.path.join(gisdbase, location_name)) or \
  509. not os.path.isdir(os.path.join(gisdbase, location_name, 'PERMANENT')) or \
  510. not os.path.isfile((os.path.join(gisdbase, location_name, 'PERMANENT',
  511. 'DEFAULT_WIND'))):
  512. fatal(_("ERROR: <%s> is not a valid GRASS location") % \
  513. os.path.join(gisdbase, location_name))
  514. else:
  515. fatal(_("Mapset <%s> doesn't exist in GRASS location <%s>. "
  516. "A new mapset can be created by '-c' switch.") % (mapset, location_name))
  517. else:
  518. # 'location' is not valid, the user wants to create
  519. # mapset on the fly
  520. if not os.access(os.path.join(gisdbase, location_name,
  521. "PERMANENT",
  522. "DEFAULT_WIND"), os.F_OK):
  523. # 'location_name' is not a valid GRASS location,
  524. # create new location and 'PERMANENT' mapset
  525. gisdbase = os.path.join(gisdbase, location_name)
  526. location_name = mapset
  527. mapset = "PERMANENT"
  528. if os.access(os.path.join(os.path.join(gisdbase,
  529. location_name,
  530. "PERMANENT",
  531. "DEFAULT_WIND")),
  532. os.F_OK):
  533. fatal(_("Failed to create new location. "
  534. "The location <%s> already exists." % location_name))
  535. if gfile('etc', 'python') not in sys.path:
  536. sys.path.append(gfile('etc', 'python'))
  537. from grass.script import core as grass
  538. try:
  539. if geofile and geofile.upper().find('EPSG:') > -1:
  540. # create location using EPSG code
  541. epsg = geofile.split(':', 1)[1]
  542. grass.create_location(gisdbase, location_name,
  543. epsg=epsg)
  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. os.environ[k] = v
  631. # Allow for mixed ISIS-GRASS Environment
  632. if os.getenv('ISISROOT'):
  633. isis = os.getenv('ISISROOT')
  634. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  635. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  636. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  637. #os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  638. libpath = os.getenv('LD_LIBRARY_PATH', '')
  639. isislibpath = os.getenv('ISIS_LIB')
  640. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  641. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  642. def set_language():
  643. # This function is used to override system default language and locale
  644. # Such override can be requested only from wxGUI
  645. # An override if user has provided correct environmental variables as
  646. # LC_MESSAGES or LANG is not necessary.
  647. # Unfortunately currently a working solution for Windows is lacking
  648. # thus it always on Vista and XP will print an error.
  649. # See discussion for Windows not following its own documentation and
  650. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  651. import locale
  652. language = 'None' # Such string sometimes is present in wx file
  653. encoding = None
  654. # Override value is stored in wxGUI preferences file.
  655. # As it's the only thing required, we'll just grep it out.
  656. try:
  657. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  658. except:
  659. # Even if there is no override, we still need to set locale.
  660. pass
  661. else:
  662. for line in fd:
  663. if re.search('^language', line):
  664. line = line.rstrip(' %s' % os.linesep)
  665. language = ''.join(line.split(';')[-1:])
  666. break
  667. fd.close()
  668. if language == 'None' or language == '' or not language:
  669. # Language override is disabled (system language specified)
  670. # As by default program runs with C locale, but users expect to
  671. # have their default locale, we'll just set default locale
  672. try:
  673. locale.setlocale(locale.LC_ALL, '')
  674. except locale.Error as e:
  675. # If we get here, system locale settings are terribly wrong
  676. # There is no point to continue as GRASS/Python will fail
  677. # in some other unpredictable way.
  678. print "System locale is not usable. It indicates misconfigured environment."
  679. print "Reported error message: %s" % e
  680. sys.exit("Fix system locale settings and then try again.")
  681. language, encoding = locale.getdefaultlocale()
  682. if not language:
  683. warning("Default locale settings are missing. GRASS running with C locale.")
  684. return
  685. else:
  686. warning("A language override has been requested. Trying to switch GRASS into '%s'..." % language)
  687. try:
  688. locale.setlocale(locale.LC_ALL, language)
  689. except locale.Error as e:
  690. try:
  691. # Locale lang.encoding might be missing. Let's try
  692. # UTF-8 encoding before giving up as on Linux systems
  693. # lang.UTF-8 locales are more common than legacy
  694. # ISO-8859 ones.
  695. encoding = 'UTF-8'
  696. normalized = locale.normalize('%s.%s' % (language, encoding))
  697. locale.setlocale(locale.LC_ALL, normalized)
  698. except locale.Error as e:
  699. # The last attempt...
  700. try:
  701. encoding = locale.getpreferredencoding()
  702. normalized = locale.normalize('%s.%s' % (language, encoding))
  703. locale.setlocale(locale.LC_ALL, normalized)
  704. except locale.Error as e:
  705. # If we got so far, attempts to set up language and locale have failed
  706. # on this system
  707. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  708. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  709. # Even if setting locale will fail, let's set LANG in a hope,
  710. # that UI will use it GRASS texts will be in selected language,
  711. # system messages (i.e. OK, Cancel etc.) - in system default
  712. # language
  713. os.environ['LANGUAGE'] = language
  714. return
  715. # Set up environment for subprocesses
  716. os.environ['LANGUAGE'] = language
  717. os.environ['LANG'] = language
  718. if encoding:
  719. normalized = locale.normalize('%s.%s' % (language, encoding))
  720. else:
  721. normalized = language
  722. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  723. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  724. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  725. os.environ[lc] = normalized
  726. # Some code in GRASS might not like other decimal separators than .
  727. # Other potential sources for problems are: LC_TIME LC_CTYPE
  728. locale.setlocale(locale.LC_NUMERIC, 'C')
  729. os.environ['LC_NUMERIC'] = 'C'
  730. if os.getenv('LC_ALL'):
  731. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  732. # From now on enforce the new language
  733. if encoding:
  734. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), codeset=encoding)
  735. else:
  736. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), unicode=True)
  737. def check_lock():
  738. global lockfile
  739. if not os.path.exists(location):
  740. fatal(_("Path '%s' doesn't exist") % location)
  741. # Check for concurrent use
  742. lockfile = os.path.join(location, ".gislock")
  743. ret = call([gfile("etc", "lock"), lockfile, "%d" % os.getpid()])
  744. if ret == 0:
  745. msg = None
  746. elif ret == 2:
  747. msg = _("%(user)s is currently running GRASS in selected mapset (" \
  748. "file %(file)s found). Concurrent use not allowed." % {
  749. 'user': user, 'file': lockfile})
  750. else:
  751. msg = _("Unable to properly access '%s'.\n"
  752. "Please notify system personel.") % lockfile
  753. if msg:
  754. if grass_gui == "wxpython":
  755. call([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "gis_set_error.py"), msg])
  756. else:
  757. global remove_lockfile
  758. remove_lockfile = False
  759. fatal(msg)
  760. def make_fontcap():
  761. fc = os.getenv('GRASS_FONT_CAP')
  762. if fc and not os.access(fc, os.R_OK):
  763. message(_("Building user fontcap..."))
  764. call(["g.mkfontcap"])
  765. def check_shell():
  766. global sh, shellname, grass_env_file
  767. # cygwin has many problems with the shell setup
  768. # below, so i hardcoded everything here.
  769. if sys.platform == 'cygwin':
  770. sh = "cygwin"
  771. shellname = "GNU Bash (Cygwin)"
  772. os.environ['SHELL'] = "/usr/bin/bash.exe"
  773. os.environ['OSTYPE'] = "cygwin"
  774. else:
  775. sh = os.path.basename(os.getenv('SHELL'))
  776. if windows and sh:
  777. sh = os.path.splitext(sh)[0]
  778. if sh == "ksh":
  779. shellname = "Korn Shell"
  780. elif sh == "csh":
  781. shellname = "C Shell"
  782. elif sh == "tcsh":
  783. shellname = "TC Shell"
  784. elif sh == "bash":
  785. shellname = "Bash Shell"
  786. elif sh == "sh":
  787. shellname = "Bourne Shell"
  788. elif sh == "zsh":
  789. shellname = "Z Shell"
  790. elif sh == "cmd":
  791. shellname = "Command Shell"
  792. else:
  793. shellname = "shell"
  794. if sh in ['csh', 'tcsh']:
  795. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  796. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  797. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  798. elif sh == 'zsh':
  799. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  800. elif sh == 'cmd':
  801. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  802. else:
  803. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  804. warning(_("Unsupported shell <%(sh)s>: %(env)s") % {'sh': sh,
  805. 'env': grass_env_file})
  806. # check for SHELL
  807. if not os.getenv('SHELL'):
  808. fatal(_("The SHELL variable is not set"))
  809. def check_batch_job():
  810. global batch_job
  811. # hack to process batch jobs:
  812. batch_job = os.getenv('GRASS_BATCH_JOB')
  813. if batch_job:
  814. # defined, but ...
  815. if not os.access(batch_job, os.F_OK):
  816. # wrong file
  817. fatal(_("Job file '%s' has been defined in "
  818. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  819. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  820. elif not os.access(batch_job, os.X_OK):
  821. # right file, but ...
  822. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  823. else:
  824. message(_("Executing '%s' ...") % batch_job)
  825. grass_gui = "text"
  826. shell = batch_job
  827. bj = Popen(shell, shell=True)
  828. bj.wait()
  829. message(_("Execution of '%s' finished.") % batch_job)
  830. def start_gui():
  831. # Start the chosen GUI but ignore text
  832. if grass_debug:
  833. message(_("GRASS GUI should be <%s>") % grass_gui)
  834. # Check for gui interface
  835. if grass_gui == "wxpython":
  836. Popen([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "wxgui.py")])
  837. def clear_screen():
  838. if windows:
  839. pass
  840. # TODO: uncomment when PDCurses works.
  841. # cls
  842. else:
  843. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug and not exit_grass:
  844. call(["tput", "clear"])
  845. def show_banner():
  846. sys.stderr.write(r"""
  847. __________ ___ __________ _______________
  848. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  849. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  850. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  851. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  852. """)
  853. def say_hello():
  854. sys.stderr.write(_("Welcome to GRASS %s") % grass_version)
  855. if grass_version.endswith('svn'):
  856. try:
  857. filerev = open(os.path.join(gisbase, 'etc', 'VERSIONNUMBER'))
  858. linerev = filerev.readline().rstrip('\n')
  859. filerev.close()
  860. revision = linerev.split(' ')[1]
  861. sys.stderr.write(' (' + revision + ')')
  862. except:
  863. pass
  864. def show_info():
  865. sys.stderr.write(
  866. r"""
  867. %-41shttp://grass.osgeo.org
  868. %-41s%s (%s)
  869. %-41sg.manual -i
  870. %-41sg.version -c
  871. """ % (_("GRASS homepage:"),
  872. _("This version running through:"),
  873. shellname, os.getenv('SHELL'),
  874. _("Help is available with the command:"),
  875. _("See the licence terms with:")))
  876. if grass_gui == 'wxpython':
  877. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  878. else:
  879. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  880. message("%-41sexit" % _("When ready to quit enter:"))
  881. message("")
  882. def csh_startup():
  883. global exit_val
  884. userhome = os.getenv('HOME') # save original home
  885. home = location
  886. os.environ['HOME'] = home
  887. cshrc = os.path.join(home, ".cshrc")
  888. tcshrc = os.path.join(home, ".tcshrc")
  889. try_remove(cshrc)
  890. try_remove(tcshrc)
  891. f = open(cshrc, 'w')
  892. f.write("set home = %s\n" % userhome)
  893. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  894. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  895. ".history"))
  896. f.write("set prompt = '\\\n")
  897. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  898. f.write("GRASS %s > '\n" % grass_version)
  899. f.write("set BOGUS=``;unset BOGUS\n")
  900. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  901. if os.access(path, os.R_OK):
  902. f.write(readfile(path) + '\n')
  903. if os.access(grass_env_file, os.R_OK):
  904. f.write(readfile(grass_env_file) + '\n')
  905. mail_re = re.compile(r"^ *set *mail *= *")
  906. for filename in [".cshrc", ".tcshrc", ".login"]:
  907. path = os.path.join(userhome, filename)
  908. if os.access(path, os.R_OK):
  909. s = readfile(path)
  910. lines = s.splitlines()
  911. for l in lines:
  912. if mail_re.match(l):
  913. f.write(l)
  914. path = os.getenv('PATH').split(':')
  915. f.write("set path = ( %s ) \n" % ' '.join(path))
  916. f.close()
  917. writefile(tcshrc, readfile(cshrc))
  918. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  919. os.environ['HOME'] = userhome
  920. def bash_startup():
  921. global exit_val
  922. # save command history in mapset dir and remember more
  923. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  924. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  925. os.environ['HISTSIZE'] = "3000"
  926. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  927. # if so, must care be taken to explicity call .grass.bashrc et al for
  928. # non-interactive bash batch jobs?
  929. userhome = os.getenv('HOME') # save original home
  930. home = location # save .bashrc in $LOCATION
  931. os.environ['HOME'] = home
  932. bashrc = os.path.join(home, ".bashrc")
  933. try_remove(bashrc)
  934. f = open(bashrc, 'w')
  935. f.write("test -r ~/.alias && . ~/.alias\n")
  936. if os.getenv('ISISROOT'):
  937. f.write("PS1='ISIS-GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  938. else:
  939. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  940. f.write("""grass_prompt() {
  941. LOCATION="`g.gisenv GISDBASE`/`g.gisenv LOCATION_NAME`/`g.gisenv MAPSET`"
  942. if test -d "$LOCATION/grid3/G3D_MASK" && test -f "$LOCATION/cell/MASK" ; then
  943. echo [%s]
  944. elif test -f "$LOCATION/cell/MASK" ; then
  945. echo [%s]
  946. elif test -d "$LOCATION/grid3/G3D_MASK" ; then
  947. echo [%s]
  948. fi
  949. }
  950. PROMPT_COMMAND=grass_prompt\n""" % (_("2D and 3D raster MASKs present"),
  951. _("Raster MASK present"),
  952. _("3D raster MASK present")))
  953. # read environmental variables
  954. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  955. if os.access(path, os.R_OK):
  956. f.write(readfile(path) + '\n')
  957. if os.access(grass_env_file, os.R_OK):
  958. f.write(readfile(grass_env_file) + '\n')
  959. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  960. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  961. f.close()
  962. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  963. os.environ['HOME'] = userhome
  964. def default_startup():
  965. global exit_val
  966. if windows:
  967. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  968. # "$ETC/run" doesn't work at all???
  969. exit_val = subprocess.call([os.getenv('SHELL')])
  970. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  971. else:
  972. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  973. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  974. if exit_val != 0:
  975. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  976. def done_message():
  977. if batch_job and os.access(batch_job, os.X_OK):
  978. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  979. message(_("Goodbye from GRASS GIS"))
  980. sys.exit(exit_val)
  981. else:
  982. message(_("Done."))
  983. message("")
  984. message(_("Goodbye from GRASS GIS"))
  985. message("")
  986. def clean_temp():
  987. message(_("Cleaning up temporary files..."))
  988. nul = open(os.devnull, 'w')
  989. call([gfile("etc", "clean_temp")], stdout=nul, stderr=nul)
  990. nul.close()
  991. def grep(string,list):
  992. expr = re.compile(string)
  993. return [elem for elem in list if expr.match(elem)]
  994. def print_params():
  995. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  996. fileplat = open(plat)
  997. linesplat = fileplat.readlines()
  998. fileplat.close()
  999. params = sys.argv[2:]
  1000. if not params:
  1001. params = ['arch', 'build', 'compiler', 'path', 'revision']
  1002. for arg in params:
  1003. if arg == 'path':
  1004. sys.stdout.write("%s\n" % gisbase)
  1005. elif arg == 'arch':
  1006. val = grep('ARCH',linesplat)
  1007. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1008. elif arg == 'build':
  1009. build = os.path.join(gisbase,'include','grass','confparms.h')
  1010. filebuild = open(build)
  1011. val = filebuild.readline()
  1012. filebuild.close()
  1013. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1014. elif arg == 'compiler':
  1015. val = grep('CC',linesplat)
  1016. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1017. elif arg == 'revision':
  1018. rev = os.path.join(gisbase,'include','grass','gis.h')
  1019. filerev = open(rev)
  1020. linesrev = filerev.readlines()
  1021. val = grep('#define GIS_H_VERSION', linesrev)
  1022. filerev.close()
  1023. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1024. else:
  1025. message(_("Parameter <%s> not supported") % arg)
  1026. def get_username():
  1027. global user
  1028. if windows:
  1029. user = os.getenv('USERNAME')
  1030. if not user:
  1031. user = "user_name"
  1032. else:
  1033. user = os.getenv('USER')
  1034. if not user:
  1035. user = os.getenv('LOGNAME')
  1036. if not user:
  1037. try:
  1038. p = Popen(['whoami'], stdout = subprocess.PIPE)
  1039. s = p.stdout.read()
  1040. p.wait()
  1041. user = s.strip()
  1042. except:
  1043. pass
  1044. if not user:
  1045. user = "user_%d" % os.getuid()
  1046. def parse_cmdline():
  1047. global args, grass_gui, create_new, exit_grass
  1048. args = []
  1049. for i in sys.argv[1:]:
  1050. # Check if the user asked for the version
  1051. if i in ["-v", "--version"]:
  1052. message('\n' + readfile(gfile("etc", "license")))
  1053. sys.exit()
  1054. # Check if the user asked for help
  1055. elif i in ["help", "-h", "-help", "--help"]:
  1056. help_message()
  1057. sys.exit()
  1058. # Check if the -text flag was given
  1059. elif i in ["-text", "--text"]:
  1060. grass_gui = 'text'
  1061. # Check if the -gtext flag was given
  1062. elif i in ["-gtext", "--gtext"]:
  1063. grass_gui = 'gtext'
  1064. # Check if the -gui flag was given
  1065. elif i in ["-gui", "--gui"]:
  1066. grass_gui = default_gui
  1067. # Check if the -wxpython flag was given
  1068. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1069. grass_gui = 'wxpython'
  1070. # Check if the user wants to create a new mapset
  1071. elif i == "-c":
  1072. create_new = True
  1073. elif i == "-e":
  1074. exit_grass = True
  1075. elif i == "--config":
  1076. print_params()
  1077. sys.exit()
  1078. else:
  1079. args.append(i)
  1080. ### MAIN script starts here
  1081. # Get the system name
  1082. windows = sys.platform == 'win32'
  1083. cygwin = "cygwin" in sys.platform
  1084. macosx = "darwin" in sys.platform
  1085. ### commented-out: broken winGRASS
  1086. # if 'GISBASE' in os.environ:
  1087. # sys.exit(_("ERROR: GRASS GIS is already running "
  1088. # "(environmental variable GISBASE found)"))
  1089. # Set GISBASE
  1090. os.environ['GISBASE'] = gisbase
  1091. # set HOME
  1092. if windows and not os.getenv('HOME'):
  1093. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  1094. os.getenv('HOMEPATH'))
  1095. # set SHELL
  1096. if windows:
  1097. if os.getenv('GRASS_SH'):
  1098. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1099. if not os.getenv('SHELL'):
  1100. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1101. atexit.register(cleanup)
  1102. # Set default GUI
  1103. default_gui = "wxpython"
  1104. # the following is only meant to be an internal variable for debugging this
  1105. # script. use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly
  1106. grass_debug = os.getenv('GRASS_DEBUG')
  1107. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  1108. os.environ['GRASS_VERSION'] = grass_version
  1109. # Set the GIS_LOCK variable to current process id
  1110. gis_lock = str(os.getpid())
  1111. os.environ['GIS_LOCK'] = gis_lock
  1112. if not os.path.exists(grass_config_dir):
  1113. os.mkdir(grass_config_dir)
  1114. # Set the global grassrc file
  1115. batch_job = os.getenv('GRASS_BATCH_JOB')
  1116. if batch_job:
  1117. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  1118. if not os.access(gisrcrc, os.R_OK):
  1119. gisrcrc = os.path.join(grass_config_dir, "rc")
  1120. else:
  1121. gisrcrc = os.path.join(grass_config_dir, "rc")
  1122. # Set the username and working directory
  1123. get_username()
  1124. # Parse the command-line options
  1125. parse_cmdline()
  1126. if exit_grass and not create_new:
  1127. fatal(_("Flag -e required also flag -c"))
  1128. # Set language
  1129. # This has to be called before any _() function call!
  1130. # Subsequent functions are using _() calls and
  1131. # thus must be called only after Language has been set.
  1132. set_language()
  1133. # Create the temporary directory and session grassrc file
  1134. create_tmp()
  1135. # Create the session grassrc file
  1136. create_gisrc()
  1137. # Set shell (needs to be called before load_env())
  1138. check_shell()
  1139. # Load environmental variables from the file
  1140. load_env()
  1141. # Ensure GUI is set
  1142. read_gui()
  1143. # Set PATH, PYTHONPATH
  1144. set_paths()
  1145. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  1146. path_prepend(gfile("lib"), ld_library_path_var)
  1147. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1148. set_defaults()
  1149. # Set GRASS_HTML_BROWSER
  1150. set_browser()
  1151. #predefine monitor size for certain architectures
  1152. if os.getenv('HOSTTYPE') == 'arm':
  1153. # small monitor on ARM (iPAQ, zaurus... etc)
  1154. os.environ['GRASS_RENDER_HEIGHT'] = "320"
  1155. os.environ['GRASS_RENDER_WIDTH'] = "240"
  1156. # First time user - GISRC is defined in the GRASS script
  1157. if not os.access(gisrc, os.F_OK):
  1158. if grass_gui == 'text' and len(args) == 0:
  1159. fatal(_("Unable to start GRASS. You can:\n"
  1160. " - Launch GRASS with '-gui' switch (`grass71 -gui`)\n"
  1161. " - Create manually GISRC file (%s)\n"
  1162. " - Launch GRASS with path to "
  1163. "the location/mapset as an argument (`grass71 /path/to/location/mapset`)") % gisrcrc)
  1164. grass_intro()
  1165. else:
  1166. clean_temp()
  1167. if create_new:
  1168. message(_("Creating new GRASS GIS location/mapset..."))
  1169. else:
  1170. message(_("Starting GRASS GIS..."))
  1171. # Check that the GUI works
  1172. check_gui()
  1173. # Parsing argument to get LOCATION
  1174. if not args:
  1175. # Try interactive startup
  1176. location = None
  1177. else:
  1178. if create_new:
  1179. if len(args) > 1:
  1180. non_interactive(args[1], args[0])
  1181. else:
  1182. non_interactive(args[0])
  1183. else:
  1184. non_interactive(args[0])
  1185. # User selects LOCATION and MAPSET if not set
  1186. set_data()
  1187. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1188. load_gisrc()
  1189. # Check .gislock file
  1190. check_lock()
  1191. # build user fontcap if specified but not present
  1192. make_fontcap()
  1193. # predefine default driver if DB connection not defined
  1194. # is this really needed?? Modules should call this when/if required.
  1195. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1196. call(['db.connect', '-c', '--quiet'])
  1197. check_batch_job()
  1198. if not batch_job and not exit_grass:
  1199. start_gui()
  1200. clear_screen()
  1201. # Display the version and license info
  1202. if batch_job:
  1203. grass_gui = 'text'
  1204. clear_screen()
  1205. clean_temp()
  1206. try_remove(lockfile)
  1207. sys.exit(0)
  1208. elif exit_grass:
  1209. clean_temp()
  1210. try_remove(lockfile)
  1211. sys.exit(0)
  1212. else:
  1213. show_banner()
  1214. say_hello()
  1215. show_info()
  1216. if grass_gui == "wxpython":
  1217. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1218. if sh in ['csh', 'tcsh']:
  1219. csh_startup()
  1220. elif sh in ['bash', 'msh', 'cygwin']:
  1221. bash_startup()
  1222. else:
  1223. default_startup()
  1224. clear_screen()
  1225. clean_env()
  1226. clean_temp()
  1227. try_remove(lockfile)
  1228. # Save GISRC
  1229. s = readfile(gisrc)
  1230. writefile(gisrcrc, s)
  1231. cleanup()
  1232. # After this point no more grass modules may be called
  1233. done_message()