grass.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  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-2015 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'))
  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. try:
  248. k, v = line.split(':', 1)
  249. except ValueError as e:
  250. sys.stderr.write(_("ERROR: Invalid line in RC file: '%s' (%s)\n") % (line, e))
  251. continue
  252. kv[k.strip()] = v.strip()
  253. f.close()
  254. return kv
  255. def read_env_file(path):
  256. kv = {}
  257. f = open(path, 'r')
  258. for line in f:
  259. k, v = line.split(':', 1)
  260. kv[k.strip()] = v.strip()
  261. f.close()
  262. return kv
  263. def write_gisrc(kv):
  264. f = open(gisrc, 'w')
  265. for k, v in kv.iteritems():
  266. f.write("%s: %s\n" % (k, v))
  267. f.close()
  268. def read_gui():
  269. global grass_gui
  270. # At this point the GRASS user interface variable has been set from the
  271. # command line, been set from an external environment variable, or is
  272. # not set. So we check if it is not set
  273. if not grass_gui:
  274. # Check for a reference to the GRASS user interface in the grassrc file
  275. if os.access(gisrc, os.R_OK):
  276. kv = read_gisrc()
  277. if 'GRASS_GUI' in os.environ:
  278. grass_gui = os.environ['GRASS_GUI']
  279. elif 'GUI' in kv:
  280. grass_gui = kv['GUI']
  281. elif 'GRASS_GUI' in kv:
  282. # For backward compatibility (GRASS_GUI renamed to GUI)
  283. grass_gui = kv['GRASS_GUI']
  284. else:
  285. # Set the GRASS user interface to the default if needed
  286. grass_gui = default_gui
  287. if not grass_gui:
  288. grass_gui = default_gui
  289. if grass_gui == 'gui':
  290. grass_gui = default_gui
  291. # FIXME oldtcltk, gis.m, d.m no longer exist
  292. if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
  293. warning(_("GUI <%s> not supported in this version") % grass_gui)
  294. grass_gui = default_gui
  295. def path_prepend(dir, var):
  296. path = os.getenv(var)
  297. if path:
  298. path = dir + os.pathsep + path
  299. else:
  300. path = dir
  301. os.environ[var] = path
  302. def path_append(dir, var):
  303. path = os.getenv(var)
  304. if path:
  305. path = path + os.pathsep + dir
  306. else:
  307. path = dir
  308. os.environ[var] = path
  309. def set_paths():
  310. # addons (path)
  311. addon_path = os.getenv('GRASS_ADDON_PATH')
  312. if addon_path:
  313. for path in addon_path.split(os.pathsep):
  314. path_prepend(addon_path, 'PATH')
  315. # addons (base)
  316. addon_base = os.getenv('GRASS_ADDON_BASE')
  317. if not addon_base:
  318. addon_base = os.path.join(grass_config_dir, 'addons')
  319. os.environ['GRASS_ADDON_BASE'] = addon_base
  320. if not windows:
  321. path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
  322. path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
  323. # standard installation
  324. if not windows:
  325. path_prepend(gfile('scripts'), 'PATH')
  326. path_prepend(gfile('bin'), 'PATH')
  327. # Set PYTHONPATH to find GRASS Python modules
  328. if os.path.exists(gfile('gui', 'wxpython')):
  329. path_prepend(gfile('gui', 'wxpython'), 'PYTHONPATH')
  330. if os.path.exists(gfile('etc', 'python')):
  331. path_prepend(gfile('etc', 'python'), 'PYTHONPATH')
  332. # set path for the GRASS man pages
  333. grass_man_path = os.path.join(gisbase, 'docs', 'man')
  334. addons_man_path = os.path.join(addon_base, 'docs', 'man')
  335. man_path = os.getenv('MANPATH')
  336. sys_man_path = None
  337. if man_path:
  338. path_prepend(addons_man_path, 'MANPATH')
  339. path_prepend(grass_man_path, 'MANPATH')
  340. else:
  341. try:
  342. nul = open(os.devnull, 'w')
  343. p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
  344. nul.close()
  345. s = p.stdout.read()
  346. p.wait()
  347. sys_man_path = s.strip()
  348. except:
  349. pass
  350. if sys_man_path:
  351. os.environ['MANPATH'] = sys_man_path
  352. path_prepend(addons_man_path, 'MANPATH')
  353. path_prepend(grass_man_path, 'MANPATH')
  354. else:
  355. os.environ['MANPATH'] = addons_man_path
  356. path_prepend(grass_man_path, 'MANPATH')
  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", "x-www-browser", "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 create_initial_gisrc():
  419. # for convenience, define GISDBASE as pwd:
  420. s = r"""GISDBASE: %s
  421. LOCATION_NAME: <UNKNOWN>
  422. MAPSET: <UNKNOWN>
  423. """ % os.getcwd()
  424. writefile(gisrc, s)
  425. def check_gui():
  426. global grass_gui, wxpython_base
  427. # Check if we are running X windows by checking the DISPLAY variable
  428. if os.getenv('DISPLAY') or windows or macosx:
  429. # Check if python is working properly
  430. if grass_gui in ('wxpython', 'gtext'):
  431. nul = open(os.devnull, 'w')
  432. p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
  433. stdout=nul, stderr=nul)
  434. nul.close()
  435. p.stdin.write("variable=True")
  436. p.stdin.close()
  437. p.wait()
  438. if p.returncode == 0:
  439. # Set the wxpython base directory
  440. wxpython_base = gfile("gui", "wxpython")
  441. else:
  442. # Python was not found - switch to text interface mode
  443. warning(_("The python command does not work as expected!\n"
  444. "Please check your GRASS_PYTHON environment variable.\n"
  445. "Use the -help option for details.\n"
  446. "Switching to text based interface mode.\n\n"
  447. "Hit RETURN to continue.\n"))
  448. sys.stdin.readline()
  449. grass_gui = 'text'
  450. else:
  451. # Display a message if a graphical interface was expected
  452. if grass_gui != 'text':
  453. # Set the interface mode to text
  454. warning(_("It appears that the X Windows system is not active.\n"
  455. "A graphical based user interface is not supported.\n"
  456. "Switching to text based interface mode.\n\n"
  457. "Hit RETURN to continue"""))
  458. sys.stdin.readline()
  459. grass_gui = 'text'
  460. # Save the user interface variable in the grassrc file - choose a temporary
  461. # file name that should not match another file
  462. if os.access(gisrc, os.F_OK):
  463. kv = read_gisrc()
  464. kv['GUI'] = grass_gui
  465. write_gisrc(kv)
  466. def non_interactive(arg, geofile=None):
  467. global gisdbase, location_name, mapset, location
  468. # Try non-interactive startup
  469. l = None
  470. if arg == '-':
  471. if location:
  472. l = location
  473. else:
  474. l = arg
  475. if l:
  476. if l == '.':
  477. l = os.getcwd()
  478. elif not os.path.isabs(l):
  479. l = os.path.abspath(l)
  480. l, mapset = os.path.split(l)
  481. if not mapset:
  482. l, mapset = os.path.split(l)
  483. l, location_name = os.path.split(l)
  484. gisdbase = l
  485. if gisdbase and location_name and mapset:
  486. location = os.path.join(gisdbase, location_name, mapset)
  487. # check if 'location' is a valid GRASS location/mapset
  488. if not os.access(os.path.join(location, "WIND"), os.R_OK):
  489. if not create_new:
  490. # 'location' is not valid, check if 'location_name' is
  491. # a valid GRASS location
  492. if not os.path.exists(os.path.join(gisdbase, location_name)):
  493. fatal(_("Location <%s> doesn't exist") % os.path.join(gisdbase, location_name))
  494. elif 'PERMANENT' not in os.listdir(os.path.join(gisdbase, location_name)) or \
  495. not os.path.isdir(os.path.join(gisdbase, location_name, 'PERMANENT')) or \
  496. not os.path.isfile((os.path.join(gisdbase, location_name, 'PERMANENT',
  497. 'DEFAULT_WIND'))):
  498. fatal(_("ERROR: <%s> is not a valid GRASS location") % \
  499. os.path.join(gisdbase, location_name))
  500. else:
  501. fatal(_("Mapset <%s> doesn't exist in GRASS location <%s>. "
  502. "A new mapset can be created by '-c' switch.") % (mapset, location_name))
  503. else:
  504. # 'location' is not valid, the user wants to create
  505. # mapset on the fly
  506. if not os.access(os.path.join(gisdbase, location_name,
  507. "PERMANENT",
  508. "DEFAULT_WIND"), os.F_OK):
  509. # 'location_name' is not a valid GRASS location,
  510. # create new location and 'PERMANENT' mapset
  511. gisdbase = os.path.join(gisdbase, location_name)
  512. location_name = mapset
  513. mapset = "PERMANENT"
  514. if os.access(os.path.join(os.path.join(gisdbase,
  515. location_name,
  516. "PERMANENT",
  517. "DEFAULT_WIND")),
  518. os.F_OK):
  519. fatal(_("Failed to create new location. "
  520. "The location <%s> already exists." % location_name))
  521. if gfile('etc', 'python') not in sys.path:
  522. sys.path.append(gfile('etc', 'python'))
  523. from grass.script import core as grass
  524. try:
  525. if geofile and geofile.upper().find('EPSG:') > -1:
  526. # create location using EPSG code
  527. epsg = geofile.split(':', 1)[1]
  528. if ':' in epsg:
  529. epsg, datum_trans = epsg.split(':', 1)
  530. else:
  531. datum_trans = None
  532. grass.create_location(gisdbase, location_name,
  533. epsg=epsg, datum_trans=datum_trans)
  534. else:
  535. # create location using georeferenced file
  536. grass.create_location(gisdbase, location_name,
  537. filename=geofile)
  538. except grass.ScriptError as e:
  539. fatal(e.value.strip('"').strip("'").replace('\\n',
  540. os.linesep))
  541. else:
  542. # 'location_name' is a valid GRASS location,
  543. # create new mapset
  544. os.mkdir(location)
  545. # copy PERMANENT/DEFAULT_WIND to <mapset>/WIND
  546. s = readfile(os.path.join(gisdbase, location_name,
  547. "PERMANENT", "DEFAULT_WIND"))
  548. writefile(os.path.join(location, "WIND"), s)
  549. message(_("Missing WIND file fixed"))
  550. if os.access(gisrc, os.R_OK):
  551. kv = read_gisrc()
  552. else:
  553. kv = {}
  554. kv['GISDBASE'] = gisdbase
  555. kv['LOCATION_NAME'] = location_name
  556. kv['MAPSET'] = mapset
  557. write_gisrc(kv)
  558. else:
  559. fatal(_("GISDBASE, LOCATION_NAME and MAPSET variables not set properly.\n"
  560. "Interactive startup needed."))
  561. def set_data():
  562. # User selects LOCATION and MAPSET if not set
  563. if not location:
  564. # Check for text interface
  565. if grass_gui == 'text':
  566. pass
  567. # Check for GUI
  568. elif grass_gui in ('gtext', 'wxpython'):
  569. gui_startup(grass_gui == 'gtext')
  570. else:
  571. # Shouldn't need this but you never know
  572. fatal(_("Invalid user interface specified - <%s>. "
  573. "Use the --help option to see valid interface names.") % grass_gui)
  574. def gui_startup(wscreen_only = False):
  575. if grass_gui in ('wxpython', 'gtext'):
  576. ret = call([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "gis_set.py")])
  577. if ret == 0:
  578. pass
  579. elif ret == 1:
  580. # The startup script printed an error message so wait
  581. # for user to read it
  582. message(_("Error in GUI startup. If necessary, please "
  583. "report this error to the GRASS developers.\n"
  584. "Switching to text mode now.\n\n"
  585. "Hit RETURN to continue..."))
  586. sys.stdin.readline()
  587. os.execlp(cmd_name, "-text")
  588. sys.exit(1)
  589. elif ret == 2:
  590. # User wants to exit from GRASS
  591. message(_("Received EXIT message from GUI.\nGRASS is not started. Bye."))
  592. sys.exit(0)
  593. else:
  594. fatal(_("Invalid return code from GUI startup script.\n"
  595. "Please advise GRASS developers of this error."))
  596. def load_gisrc():
  597. global gisdbase, location_name, mapset, location
  598. kv = read_gisrc()
  599. gisdbase = kv.get('GISDBASE')
  600. location_name = kv.get('LOCATION_NAME')
  601. mapset = kv.get('MAPSET')
  602. if not gisdbase or not location_name or not mapset:
  603. fatal(_("Error reading data path information from g.gisenv.\n"
  604. "GISDBASE=%(gisbase)s\n"
  605. "LOCATION_NAME=%(location)s\n"
  606. "MAPSET=%(mapset)s\n\n"
  607. "Check the <%s(file)> file." % \
  608. {'gisbase': gisdbase, 'location': location_name,
  609. 'mapset': mapset, 'file': gisrcrc}))
  610. location = os.path.join(gisdbase, location_name, mapset)
  611. # load environmental variables from grass_env_file
  612. def load_env():
  613. if not os.access(grass_env_file, os.R_OK):
  614. return
  615. for line in readfile(grass_env_file).split(os.linesep):
  616. try:
  617. k, v = map(lambda x: x.strip(), line.strip().split(' ', 1)[1].split('=', 1))
  618. except:
  619. continue
  620. evalue = os.getenv(k)
  621. if evalue:
  622. if k == 'GRASS_ADDON_PATH':
  623. os.environ[k] = evalue + os.pathsep + v
  624. else:
  625. warning(_("Environmental variable '%s' already set, ignoring value '%s'") % \
  626. (k, v))
  627. else:
  628. os.environ[k] = v
  629. # Allow for mixed ISIS-GRASS Environment
  630. if os.getenv('ISISROOT'):
  631. isis = os.getenv('ISISROOT')
  632. os.environ['ISIS_LIB'] = isis + os.sep + "lib"
  633. os.environ['ISIS_3RDPARTY'] = isis + os.sep + "3rdParty" + os.sep + "lib"
  634. os.environ['QT_PLUGIN_PATH'] = isis + os.sep + "3rdParty" + os.sep + "plugins"
  635. #os.environ['ISIS3DATA'] = isis + "$ISIS3DATA"
  636. libpath = os.getenv('LD_LIBRARY_PATH', '')
  637. isislibpath = os.getenv('ISIS_LIB')
  638. isis3rdparty = os.getenv('ISIS_3RDPARTY')
  639. os.environ['LD_LIBRARY_PATH'] = libpath + os.pathsep + isislibpath + os.pathsep + isis3rdparty
  640. def set_language():
  641. # This function is used to override system default language and locale
  642. # Such override can be requested only from wxGUI
  643. # An override if user has provided correct environmental variables as
  644. # LC_MESSAGES or LANG is not necessary.
  645. # Unfortunately currently a working solution for Windows is lacking
  646. # thus it always on Vista and XP will print an error.
  647. # See discussion for Windows not following its own documentation and
  648. # not accepting ISO codes as valid locale identifiers http://bugs.python.org/issue10466
  649. import locale
  650. language = 'None' # Such string sometimes is present in wx file
  651. encoding = None
  652. # Override value is stored in wxGUI preferences file.
  653. # As it's the only thing required, we'll just grep it out.
  654. try:
  655. fd = open(os.path.join(grass_config_dir, 'wx'), 'r')
  656. except:
  657. # Even if there is no override, we still need to set locale.
  658. pass
  659. else:
  660. for line in fd:
  661. if re.search('^language', line):
  662. line = line.rstrip(' %s' % os.linesep)
  663. language = ''.join(line.split(';')[-1:])
  664. break
  665. fd.close()
  666. if language == 'None' or language == '' or not language:
  667. # Language override is disabled (system language specified)
  668. # As by default program runs with C locale, but users expect to
  669. # have their default locale, we'll just set default locale
  670. try:
  671. locale.setlocale(locale.LC_ALL, '')
  672. except locale.Error as e:
  673. # If we get here, system locale settings are terribly wrong
  674. # There is no point to continue as GRASS/Python will fail
  675. # in some other unpredictable way.
  676. print "System locale is not usable. It indicates misconfigured environment."
  677. print "Reported error message: %s" % e
  678. sys.exit("Fix system locale settings and then try again.")
  679. language, encoding = locale.getdefaultlocale()
  680. if not language:
  681. warning(_("Default locale settings are missing. GRASS running with C locale."))
  682. return
  683. else:
  684. if grass_debug:
  685. message(_("A language override has been requested. Trying to switch GRASS into '%s'...") % language)
  686. try:
  687. locale.setlocale(locale.LC_ALL, language)
  688. except locale.Error as e:
  689. try:
  690. # Locale lang.encoding might be missing. Let's try
  691. # UTF-8 encoding before giving up as on Linux systems
  692. # lang.UTF-8 locales are more common than legacy
  693. # ISO-8859 ones.
  694. encoding = 'UTF-8'
  695. normalized = locale.normalize('%s.%s' % (language, encoding))
  696. locale.setlocale(locale.LC_ALL, normalized)
  697. except locale.Error as e:
  698. # The last attempt...
  699. try:
  700. encoding = locale.getpreferredencoding()
  701. normalized = locale.normalize('%s.%s' % (language, encoding))
  702. locale.setlocale(locale.LC_ALL, normalized)
  703. except locale.Error as e:
  704. # If we got so far, attempts to set up language and locale have failed
  705. # on this system
  706. sys.stderr.write("Failed to enforce user specified language '%s' with error: '%s'\n" % (language, e))
  707. sys.stderr.write("A LANGUAGE environmental variable has been set.\nPart of messages will be displayed in the requested language.\n")
  708. # Even if setting locale will fail, let's set LANG in a hope,
  709. # that UI will use it GRASS texts will be in selected language,
  710. # system messages (i.e. OK, Cancel etc.) - in system default
  711. # language
  712. os.environ['LANGUAGE'] = language
  713. return
  714. # Set up environment for subprocesses
  715. os.environ['LANGUAGE'] = language
  716. os.environ['LANG'] = language
  717. if encoding:
  718. normalized = locale.normalize('%s.%s' % (language, encoding))
  719. else:
  720. normalized = language
  721. for lc in ('LC_CTYPE', 'LC_MESSAGES', 'LC_TIME', 'LC_COLLATE',
  722. 'LC_MONETARY', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
  723. 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION'):
  724. os.environ[lc] = normalized
  725. # Some code in GRASS might not like other decimal separators than .
  726. # Other potential sources for problems are: LC_TIME LC_CTYPE
  727. locale.setlocale(locale.LC_NUMERIC, 'C')
  728. os.environ['LC_NUMERIC'] = 'C'
  729. if os.getenv('LC_ALL'):
  730. del os.environ['LC_ALL'] # Remove LC_ALL to not override LC_NUMERIC
  731. # From now on enforce the new language
  732. if encoding:
  733. gettext.install('grasslibs', os.path.join(gisbase, 'locale'), codeset=encoding)
  734. else:
  735. gettext.install('grasslibs', os.path.join(gisbase, 'locale'))
  736. def check_lock():
  737. global lockfile
  738. if not os.path.exists(location):
  739. fatal(_("Path '%s' doesn't exist") % location)
  740. # Check for concurrent use
  741. lockfile = os.path.join(location, ".gislock")
  742. ret = call([gfile("etc", "lock"), lockfile, "%d" % os.getpid()])
  743. if ret == 0:
  744. msg = None
  745. elif ret == 2:
  746. msg = _("%(user)s is currently running GRASS in selected mapset (" \
  747. "file %(file)s found). Concurrent use not allowed." % {
  748. 'user': user, 'file': lockfile})
  749. else:
  750. msg = _("Unable to properly access '%s'.\n"
  751. "Please notify system personel.") % lockfile
  752. if msg:
  753. if grass_gui == "wxpython":
  754. call([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "gis_set_error.py"), msg])
  755. else:
  756. global remove_lockfile
  757. remove_lockfile = False
  758. fatal(msg)
  759. def make_fontcap():
  760. fc = os.getenv('GRASS_FONT_CAP')
  761. if fc and not os.access(fc, os.R_OK):
  762. message(_("Building user fontcap..."))
  763. call(["g.mkfontcap"])
  764. def check_shell():
  765. global sh, shellname, grass_env_file
  766. # cygwin has many problems with the shell setup
  767. # below, so i hardcoded everything here.
  768. if sys.platform == 'cygwin':
  769. sh = "cygwin"
  770. shellname = "GNU Bash (Cygwin)"
  771. os.environ['SHELL'] = "/usr/bin/bash.exe"
  772. os.environ['OSTYPE'] = "cygwin"
  773. else:
  774. # in docker the 'SHELL' variable may not be
  775. # visible in a Python session
  776. try:
  777. sh = os.path.basename(os.getenv('SHELL'))
  778. except:
  779. sh = 'sh'
  780. os.environ['SHELL'] = sh
  781. if windows and sh:
  782. sh = os.path.splitext(sh)[0]
  783. if sh == "ksh":
  784. shellname = "Korn Shell"
  785. elif sh == "csh":
  786. shellname = "C Shell"
  787. elif sh == "tcsh":
  788. shellname = "TC Shell"
  789. elif sh == "bash":
  790. shellname = "Bash Shell"
  791. elif sh == "sh":
  792. shellname = "Bourne Shell"
  793. elif sh == "zsh":
  794. shellname = "Z Shell"
  795. elif sh == "cmd":
  796. shellname = "Command Shell"
  797. else:
  798. shellname = "shell"
  799. if sh in ['csh', 'tcsh']:
  800. grass_env_file = os.path.join(grass_config_dir, 'cshrc')
  801. elif sh in ['bash', 'msh', 'cygwin', 'sh']:
  802. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  803. elif sh == 'zsh':
  804. grass_env_file = os.path.join(grass_config_dir, 'zshrc')
  805. elif sh == 'cmd':
  806. grass_env_file = os.path.join(grass_config_dir, 'env.bat')
  807. else:
  808. grass_env_file = os.path.join(grass_config_dir, 'bashrc')
  809. warning(_("Unsupported shell <%(sh)s>: %(env)s") % {'sh': sh,
  810. 'env': grass_env_file})
  811. # check for SHELL
  812. if not os.getenv('SHELL'):
  813. fatal(_("The SHELL variable is not set"))
  814. def check_batch_job():
  815. global batch_job
  816. # hack to process batch jobs:
  817. batch_job = os.getenv('GRASS_BATCH_JOB')
  818. if batch_job:
  819. # defined, but ...
  820. if not os.access(batch_job, os.F_OK):
  821. # wrong file
  822. fatal(_("Job file '%s' has been defined in "
  823. "the 'GRASS_BATCH_JOB' variable but not found. Exiting.\n\n"
  824. "Use 'unset GRASS_BATCH_JOB' to disable batch job processing.") % batch_job)
  825. elif not os.access(batch_job, os.X_OK):
  826. # right file, but ...
  827. fatal(_("Change file permission to 'executable' for '%s'") % batch_job)
  828. else:
  829. message(_("Executing '%s' ...") % batch_job)
  830. grass_gui = "text"
  831. shell = batch_job
  832. bj = Popen(shell, shell=True)
  833. bj.wait()
  834. message(_("Execution of '%s' finished.") % batch_job)
  835. def start_gui():
  836. # Start the chosen GUI but ignore text
  837. if grass_debug:
  838. message(_("GRASS GUI should be <%s>") % grass_gui)
  839. # Check for gui interface
  840. if grass_gui == "wxpython":
  841. Popen([os.getenv('GRASS_PYTHON'), gfile(wxpython_base, "wxgui.py")])
  842. def clear_screen():
  843. if windows:
  844. pass
  845. # TODO: uncomment when PDCurses works.
  846. # cls
  847. else:
  848. if not os.getenv('GRASS_BATCH_JOB') and not grass_debug and not exit_grass:
  849. call(["tput", "clear"])
  850. def show_banner():
  851. sys.stderr.write(r"""
  852. __________ ___ __________ _______________
  853. / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/
  854. / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \
  855. / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ /
  856. \____/_/ |_/_/ |_/____/____/ \____/___//____/
  857. """)
  858. def say_hello():
  859. sys.stderr.write(_("Welcome to GRASS GIS %s") % grass_version)
  860. if grass_version.endswith('svn'):
  861. try:
  862. filerev = open(os.path.join(gisbase, 'etc', 'VERSIONNUMBER'))
  863. linerev = filerev.readline().rstrip('\n')
  864. filerev.close()
  865. revision = linerev.split(' ')[1]
  866. sys.stderr.write(' (' + revision + ')')
  867. except:
  868. pass
  869. def show_info():
  870. sys.stderr.write(
  871. r"""
  872. %-41shttp://grass.osgeo.org
  873. %-41s%s (%s)
  874. %-41sg.manual -i
  875. %-41sg.version -c
  876. """ % (_("GRASS GIS homepage:"),
  877. _("This version running through:"),
  878. shellname, os.getenv('SHELL'),
  879. _("Help is available with the command:"),
  880. _("See the licence terms with:")))
  881. if grass_gui == 'wxpython':
  882. message("%-41sg.gui wxpython" % _("If required, restart the GUI with:"))
  883. else:
  884. message("%-41sg.gui %s" % (_("Start the GUI with:"), default_gui))
  885. message("%-41sexit" % _("When ready to quit enter:"))
  886. message("")
  887. def csh_startup():
  888. global exit_val
  889. userhome = os.getenv('HOME') # save original home
  890. home = location
  891. os.environ['HOME'] = home
  892. cshrc = os.path.join(home, ".cshrc")
  893. tcshrc = os.path.join(home, ".tcshrc")
  894. try_remove(cshrc)
  895. try_remove(tcshrc)
  896. f = open(cshrc, 'w')
  897. f.write("set home = %s\n" % userhome)
  898. f.write("set history = 3000 savehist = 3000 noclobber ignoreeof\n")
  899. f.write("set histfile = %s\n" % os.path.join(os.getenv('HOME'),
  900. ".history"))
  901. f.write("set prompt = '\\\n")
  902. f.write("Mapset <%s> in Location <%s> \\\n" % (mapset, location_name))
  903. f.write("GRASS GIS %s > '\n" % grass_version)
  904. f.write("set BOGUS=``;unset BOGUS\n")
  905. path = os.path.join(userhome, ".grass.cshrc") # left for backward compatibility
  906. if os.access(path, os.R_OK):
  907. f.write(readfile(path) + '\n')
  908. if os.access(grass_env_file, os.R_OK):
  909. f.write(readfile(grass_env_file) + '\n')
  910. mail_re = re.compile(r"^ *set *mail *= *")
  911. for filename in [".cshrc", ".tcshrc", ".login"]:
  912. path = os.path.join(userhome, filename)
  913. if os.access(path, os.R_OK):
  914. s = readfile(path)
  915. lines = s.splitlines()
  916. for l in lines:
  917. if mail_re.match(l):
  918. f.write(l)
  919. path = os.getenv('PATH').split(':')
  920. f.write("set path = ( %s ) \n" % ' '.join(path))
  921. f.close()
  922. writefile(tcshrc, readfile(cshrc))
  923. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  924. os.environ['HOME'] = userhome
  925. def bash_startup():
  926. global exit_val
  927. # save command history in mapset dir and remember more
  928. os.environ['HISTFILE'] = os.path.join(location, ".bash_history")
  929. if not os.getenv('HISTSIZE') and not os.getenv('HISTFILESIZE'):
  930. os.environ['HISTSIZE'] = "3000"
  931. # instead of changing $HOME, start bash with: --rcfile "$LOCATION/.bashrc" ?
  932. # if so, must care be taken to explicity call .grass.bashrc et al for
  933. # non-interactive bash batch jobs?
  934. userhome = os.getenv('HOME') # save original home
  935. home = location # save .bashrc in $LOCATION
  936. os.environ['HOME'] = home
  937. bashrc = os.path.join(home, ".bashrc")
  938. try_remove(bashrc)
  939. f = open(bashrc, 'w')
  940. f.write("test -r ~/.alias && . ~/.alias\n")
  941. if os.getenv('ISISROOT'):
  942. f.write("PS1='ISIS-GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  943. else:
  944. f.write("PS1='GRASS %s (%s):\w > '\n" % (grass_version, location_name))
  945. f.write("""grass_prompt() {
  946. LOCATION="`g.gisenv get=GISDBASE,LOCATION_NAME,MAPSET separator='/'`"
  947. if test -d "$LOCATION/grid3/G3D_MASK" && test -f "$LOCATION/cell/MASK" ; then
  948. echo [%s]
  949. elif test -f "$LOCATION/cell/MASK" ; then
  950. echo [%s]
  951. elif test -d "$LOCATION/grid3/G3D_MASK" ; then
  952. echo [%s]
  953. fi
  954. }
  955. PROMPT_COMMAND=grass_prompt\n""" % (_("2D and 3D raster MASKs present"),
  956. _("Raster MASK present"),
  957. _("3D raster MASK present")))
  958. # read environmental variables
  959. path = os.path.join(userhome, ".grass.bashrc") # left for backward compatibility
  960. if os.access(path, os.R_OK):
  961. f.write(readfile(path) + '\n')
  962. for env in os.environ.keys():
  963. if env.startswith('GRASS'):
  964. val = os.environ[env]
  965. if ' ' in val:
  966. val = '"%s"' % val
  967. f.write('export %s=%s\n' % (env, val))
  968. ### Replaced by code above (do not override already set up environment variables)
  969. ### if os.access(grass_env_file, os.R_OK):
  970. ### f.write(readfile(grass_env_file) + '\n')
  971. f.write("export PATH=\"%s\"\n" % os.getenv('PATH'))
  972. f.write("export HOME=\"%s\"\n" % userhome) # restore user home path
  973. f.close()
  974. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  975. os.environ['HOME'] = userhome
  976. def default_startup():
  977. global exit_val
  978. if windows:
  979. os.environ['PS1'] = "GRASS %s> " % (grass_version)
  980. # "$ETC/run" doesn't work at all???
  981. exit_val = subprocess.call([os.getenv('SHELL')])
  982. cleanup_dir(os.path.join(location, ".tmp")) # remove GUI session files from .tmp
  983. else:
  984. os.environ['PS1'] = "GRASS %s (%s):\w > " % (grass_version, location_name)
  985. exit_val = call([gfile("etc", "run"), os.getenv('SHELL')])
  986. if exit_val != 0:
  987. fatal(_("Failed to start shell '%s'") % os.getenv('SHELL'))
  988. def done_message():
  989. if batch_job and os.access(batch_job, os.X_OK):
  990. message(_("Batch job '%s' (defined in GRASS_BATCH_JOB variable) was executed.") % batch_job)
  991. message(_("Goodbye from GRASS GIS"))
  992. sys.exit(exit_val)
  993. else:
  994. message(_("Done."))
  995. message("")
  996. message(_("Goodbye from GRASS GIS"))
  997. message("")
  998. def clean_temp():
  999. message(_("Cleaning up temporary files..."))
  1000. nul = open(os.devnull, 'w')
  1001. call([gfile("etc", "clean_temp")], stdout=nul, stderr=nul)
  1002. nul.close()
  1003. def grep(string,list):
  1004. expr = re.compile(string)
  1005. return [elem for elem in list if expr.match(elem)]
  1006. def print_params():
  1007. plat = gfile(gisbase, 'include', 'Make', 'Platform.make')
  1008. fileplat = open(plat)
  1009. linesplat = fileplat.readlines()
  1010. fileplat.close()
  1011. params = sys.argv[2:]
  1012. if not params:
  1013. params = ['arch', 'build', 'compiler', 'path', 'revision']
  1014. for arg in params:
  1015. if arg == 'path':
  1016. sys.stdout.write("%s\n" % gisbase)
  1017. elif arg == 'arch':
  1018. val = grep('ARCH',linesplat)
  1019. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1020. elif arg == 'build':
  1021. build = os.path.join(gisbase,'include','grass','confparms.h')
  1022. filebuild = open(build)
  1023. val = filebuild.readline()
  1024. filebuild.close()
  1025. sys.stdout.write("%s\n" % val.strip().strip('"').strip())
  1026. elif arg == 'compiler':
  1027. val = grep('CC',linesplat)
  1028. sys.stdout.write("%s\n" % val[0].split('=')[1].strip())
  1029. elif arg == 'revision':
  1030. rev = os.path.join(gisbase,'include','grass','gis.h')
  1031. filerev = open(rev)
  1032. linesrev = filerev.readlines()
  1033. val = grep('#define GIS_H_VERSION', linesrev)
  1034. filerev.close()
  1035. sys.stdout.write("%s\n" % val[0].split(':')[1].rstrip('$"\n').strip())
  1036. else:
  1037. message(_("Parameter <%s> not supported") % arg)
  1038. def get_username():
  1039. global user
  1040. if windows:
  1041. user = os.getenv('USERNAME')
  1042. if not user:
  1043. user = "user_name"
  1044. else:
  1045. user = os.getenv('USER')
  1046. if not user:
  1047. user = os.getenv('LOGNAME')
  1048. if not user:
  1049. try:
  1050. p = Popen(['whoami'], stdout = subprocess.PIPE)
  1051. s = p.stdout.read()
  1052. p.wait()
  1053. user = s.strip()
  1054. except:
  1055. pass
  1056. if not user:
  1057. user = "user_%d" % os.getuid()
  1058. def parse_cmdline():
  1059. global args, grass_gui, create_new, exit_grass
  1060. args = []
  1061. for i in sys.argv[1:]:
  1062. # Check if the user asked for the version
  1063. if i in ["-v", "--version"]:
  1064. message("GRASS GIS %s" % grass_version)
  1065. message('\n' + readfile(gfile("etc", "license")))
  1066. sys.exit()
  1067. # Check if the user asked for help
  1068. elif i in ["help", "-h", "-help", "--help"]:
  1069. help_message()
  1070. sys.exit()
  1071. # Check if the -text flag was given
  1072. elif i in ["-text", "--text"]:
  1073. grass_gui = 'text'
  1074. # Check if the -gtext flag was given
  1075. elif i in ["-gtext", "--gtext"]:
  1076. grass_gui = 'gtext'
  1077. # Check if the -gui flag was given
  1078. elif i in ["-gui", "--gui"]:
  1079. grass_gui = default_gui
  1080. # Check if the -wxpython flag was given
  1081. elif i in ["-wxpython", "-wx", "--wxpython", "--wx"]:
  1082. grass_gui = 'wxpython'
  1083. # Check if the user wants to create a new mapset
  1084. elif i == "-c":
  1085. create_new = True
  1086. elif i == "-e":
  1087. exit_grass = True
  1088. elif i == "--config":
  1089. print_params()
  1090. sys.exit()
  1091. else:
  1092. args.append(i)
  1093. ### MAIN script starts here
  1094. # Get the system name
  1095. windows = sys.platform == 'win32'
  1096. cygwin = "cygwin" in sys.platform
  1097. macosx = "darwin" in sys.platform
  1098. ### commented-out: broken winGRASS
  1099. # if 'GISBASE' in os.environ:
  1100. # sys.exit(_("ERROR: GRASS GIS is already running "
  1101. # "(environmental variable GISBASE found)"))
  1102. # Set GISBASE
  1103. os.environ['GISBASE'] = gisbase
  1104. # set HOME
  1105. if windows and not os.getenv('HOME'):
  1106. os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
  1107. os.getenv('HOMEPATH'))
  1108. # set SHELL
  1109. if windows:
  1110. if os.getenv('GRASS_SH'):
  1111. os.environ['SHELL'] = os.getenv('GRASS_SH')
  1112. if not os.getenv('SHELL'):
  1113. os.environ['SHELL'] = os.getenv('COMSPEC', 'cmd.exe')
  1114. atexit.register(cleanup)
  1115. # Set default GUI
  1116. default_gui = "wxpython"
  1117. # the following is only meant to be an internal variable for debugging this
  1118. # script. use 'g.gisenv set="DEBUG=[0-5]"' to turn GRASS debug mode on properly
  1119. grass_debug = os.getenv('GRASS_DEBUG')
  1120. # Set GRASS version number for R interface etc (must be an env_var for MS-Windows)
  1121. os.environ['GRASS_VERSION'] = grass_version
  1122. # Set the GIS_LOCK variable to current process id
  1123. gis_lock = str(os.getpid())
  1124. os.environ['GIS_LOCK'] = gis_lock
  1125. if not os.path.exists(grass_config_dir):
  1126. os.mkdir(grass_config_dir)
  1127. # Set the global grassrc file
  1128. batch_job = os.getenv('GRASS_BATCH_JOB')
  1129. if batch_job:
  1130. gisrcrc = os.path.join(grass_config_dir, "rc.%s" % platform.node())
  1131. if not os.access(gisrcrc, os.R_OK):
  1132. gisrcrc = os.path.join(grass_config_dir, "rc")
  1133. else:
  1134. gisrcrc = os.path.join(grass_config_dir, "rc")
  1135. # Set the username and working directory
  1136. get_username()
  1137. # Parse the command-line options
  1138. parse_cmdline()
  1139. if exit_grass and not create_new:
  1140. fatal(_("Flag -e required also flag -c"))
  1141. # Set language
  1142. # This has to be called before any _() function call!
  1143. # Subsequent functions are using _() calls and
  1144. # thus must be called only after Language has been set.
  1145. set_language()
  1146. # Create the temporary directory and session grassrc file
  1147. create_tmp()
  1148. # Create the session grassrc file
  1149. create_gisrc()
  1150. # Set shell (needs to be called before load_env())
  1151. check_shell()
  1152. # Load environmental variables from the file
  1153. load_env()
  1154. # Ensure GUI is set
  1155. read_gui()
  1156. # Set PATH, PYTHONPATH
  1157. set_paths()
  1158. # Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
  1159. path_prepend(gfile("lib"), ld_library_path_var)
  1160. # Set GRASS_PAGER, GRASS_PYTHON, GRASS_GNUPLOT, GRASS_PROJSHARE
  1161. set_defaults()
  1162. # Set GRASS_HTML_BROWSER
  1163. set_browser()
  1164. #predefine monitor size for certain architectures
  1165. if os.getenv('HOSTTYPE') == 'arm':
  1166. # small monitor on ARM (iPAQ, zaurus... etc)
  1167. os.environ['GRASS_RENDER_HEIGHT'] = "320"
  1168. os.environ['GRASS_RENDER_WIDTH'] = "240"
  1169. # First time user - GISRC is defined in the GRASS script
  1170. if not os.access(gisrc, os.F_OK):
  1171. if grass_gui == 'text' and len(args) == 0:
  1172. fatal(_("Unable to start GRASS. You can:\n"
  1173. " - Launch GRASS with '-gui' switch (`grass70 -gui`)\n"
  1174. " - Create manually GISRC file (%s)\n"
  1175. " - Launch GRASS with path to "
  1176. "the location/mapset as an argument (`grass70 /path/to/location/mapset`)") % gisrcrc)
  1177. create_initial_gisrc()
  1178. else:
  1179. clean_temp()
  1180. if create_new:
  1181. message(_("Creating new GRASS GIS location/mapset..."))
  1182. else:
  1183. message(_("Starting GRASS GIS..."))
  1184. # Check that the GUI works
  1185. check_gui()
  1186. # Parsing argument to get LOCATION
  1187. if not args:
  1188. # Try interactive startup
  1189. location = None
  1190. else:
  1191. if create_new:
  1192. if len(args) > 1:
  1193. non_interactive(args[1], args[0])
  1194. else:
  1195. non_interactive(args[0])
  1196. else:
  1197. non_interactive(args[0])
  1198. # User selects LOCATION and MAPSET if not set
  1199. set_data()
  1200. # Set GISDBASE, LOCATION_NAME, MAPSET, LOCATION from $GISRC
  1201. load_gisrc()
  1202. # Check .gislock file
  1203. check_lock()
  1204. # build user fontcap if specified but not present
  1205. make_fontcap()
  1206. # predefine default driver if DB connection not defined
  1207. # is this really needed?? Modules should call this when/if required.
  1208. if not os.access(os.path.join(location, "VAR"), os.F_OK):
  1209. call(['db.connect', '-c', '--quiet'])
  1210. check_batch_job()
  1211. if not batch_job and not exit_grass:
  1212. start_gui()
  1213. clear_screen()
  1214. # Display the version and license info
  1215. if batch_job:
  1216. grass_gui = 'text'
  1217. clear_screen()
  1218. clean_temp()
  1219. try_remove(lockfile)
  1220. sys.exit(0)
  1221. elif exit_grass:
  1222. clean_temp()
  1223. try_remove(lockfile)
  1224. sys.exit(0)
  1225. else:
  1226. show_banner()
  1227. say_hello()
  1228. show_info()
  1229. if grass_gui == "wxpython":
  1230. message(_("Launching <%s> GUI in the background, please wait...") % grass_gui)
  1231. if sh in ['csh', 'tcsh']:
  1232. csh_startup()
  1233. elif sh in ['bash', 'msh', 'cygwin']:
  1234. bash_startup()
  1235. else:
  1236. default_startup()
  1237. clear_screen()
  1238. clean_env()
  1239. clean_temp()
  1240. try_remove(lockfile)
  1241. # Save GISRC
  1242. s = readfile(gisrc)
  1243. writefile(gisrcrc, s)
  1244. cleanup()
  1245. # After this point no more grass modules may be called
  1246. done_message()