grass.py 50 KB

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