grass.py 48 KB

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