-
-
Notifications
You must be signed in to change notification settings - Fork 333
/
Copy pathgrass.py
2397 lines (2068 loc) · 90.2 KB
/
grass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#############################################################################
#
# MODULE: GRASS initialization script
# AUTHOR(S): Original author unknown - probably CERL
# Andreas Lange <andreas.lange rhein-main.de>
# Huidae Cho <grass4u gmail.com>
# Justin Hickey <jhickey hpcc.nectec.or.th>
# Markus Neteler <neteler osgeo.org>
# Hamish Bowman <hamish_b yahoo.com>
#
# GRASS 7: converted to Python (based on init.sh shell
# script from GRASS 6) by Glynn Clements
# Martin Landa <landa.martin gmail.com>
# Luca Delucchi <lucadeluge gmail.com>
# Vaclav Petras <wenzeslaus gmail.com> (refactoring and exec)
# PURPOSE: Sets up environment variables, parses any remaining
# command line options for setting the GISDBASE, LOCATION,
# and/or MAPSET. Finally it starts GRASS with the appropriate
# user interface and cleans up after it is finished.
# COPYRIGHT: (C) 2000-2019 by the GRASS Development Team
#
# This program is free software under the GNU General
# Public License (>=v2). Read the file COPYING that
# comes with GRASS for details.
#
#############################################################################
"""
Script to run GRASS session.
Some of the functions could be used separately but import from this module
is not safe, i.e. it has side effects (this should be changed in the future).
"""
# we allow for long file because we want to avoid imports if possible
# (this makes it more stable since we have to set up paths first)
# pylint: disable=too-many-lines
from __future__ import print_function
import sys
import os
import errno
import atexit
import gettext
import shutil
import signal
import string
import subprocess
import types
import re
import six
import platform
import tempfile
import locale
import uuid
# mechanism meant for debugging this script (only)
# private global to store if we are debugging
_DEBUG = None
# for wxpath
_WXPYTHON_BASE = None
ENCODING = locale.getdefaultlocale()[1]
if ENCODING is None:
ENCODING = 'UTF-8'
print("Default locale not found, using UTF-8") # intentionally not translatable
# The "@...@" variables are being substituted during build process
#
# TODO: should GISBASE be renamed to something like GRASS_PATH?
# GISBASE marks complete runtime, so no need to get it here when
# setting it up, possible scenario: existing runtime and starting
# GRASS in that, we want to overwrite the settings, not to take it
# possibly same for GRASS_PROJSHARE and others but maybe not
#
# We need to simultaneously make sure that:
# - we get GISBASE from os.environ if it is defined (doesn't this mean that we are already
# inside a GRASS session? If we are, why do we need to run this script again???).
# - GISBASE exists as an ENV variable
#
# pmav99: Ugly as hell, but that's what the code before the refactoring was doing.
if 'GISBASE' in os.environ and len(os.getenv('GISBASE')) > 0:
GISBASE = os.path.normpath(os.environ["GISBASE"])
else:
GISBASE = os.path.normpath("@GISBASE@")
os.environ['GISBASE'] = GISBASE
CMD_NAME = "@START_UP@"
GRASS_VERSION = "@GRASS_VERSION_NUMBER@"
LD_LIBRARY_PATH_VAR = '@LD_LIBRARY_PATH_VAR@'
CONFIG_PROJSHARE = os.environ.get('GRASS_PROJSHARE', "@CONFIG_PROJSHARE@")
# Get the system name
WINDOWS = sys.platform == 'win32'
CYGWIN = "cygwin" in sys.platform
MACOSX = "darwin" in sys.platform
def decode(bytes_, encoding=ENCODING):
"""Decode bytes with default locale and return (unicode) string
Adapted from lib/python/core/utils.py
No-op if parameter is not bytes (assumed unicode string).
:param bytes bytes_: the bytes to decode
:param encoding: encoding to be used, default value is the system's default
encoding or, if that cannot be determined, 'UTF-8'.
"""
if sys.version_info.major >= 3:
unicode = str
if isinstance(bytes_, unicode):
return bytes_
elif isinstance(bytes_, bytes):
return bytes_.decode(encoding)
else:
# if something else than text
raise TypeError("can only accept types str and bytes")
def encode(string, encoding=ENCODING):
"""Encode string with default locale and return bytes with that encoding
Adapted from lib/python/core/utils.py
No-op if parameter is bytes (assumed already encoded).
This ensures garbage in, garbage out.
:param str string: the string to encode
:param encoding: encoding to be used, default value is the system's default
encoding or, if that cannot be determined, 'UTF-8'.
"""
if sys.version_info.major >= 3:
unicode = str
if isinstance(string, bytes):
return string
# this also tests str in Py3:
elif isinstance(string, unicode):
return string.encode(encoding)
else:
# if something else than text
raise TypeError("can only accept types str and bytes")
# see https://trac.osgeo.org/grass/ticket/3508
def to_text_string(obj, encoding=ENCODING):
"""Convert `obj` to (unicode) text string"""
if six.PY2:
# Python 2
return encode(obj, encoding=encoding)
else:
# Python 3
return decode(obj, encoding=encoding)
def try_remove(path):
try:
os.remove(path)
except:
pass
def clean_env():
gisrc = os.environ['GISRC']
env_curr = read_gisrc(gisrc)
env_new = {}
for k, v in env_curr.items():
if k.endswith('PID') or k.startswith('MONITOR'):
continue
env_new[k] = v
write_gisrc(env_new, gisrc)
def is_debug():
"""Returns True if we are in debug mode
For debug messages use ``debug()``.
"""
global _DEBUG
if _DEBUG is not None:
return _DEBUG
_DEBUG = os.getenv('GRASS_DEBUG')
# translate to bool (no or empty variable means false)
if _DEBUG:
_DEBUG = True
else:
_DEBUG = False
return _DEBUG
def debug(msg):
"""Print a debug message if in debug mode
Do not use translatable strings for debug messages.
"""
if is_debug():
sys.stderr.write("DEBUG: %s\n" % msg)
sys.stderr.flush()
def message(msg):
sys.stderr.write(msg + "\n")
sys.stderr.flush()
def warning(text):
sys.stderr.write(_("WARNING") + ': ' + text + os.linesep)
def fatal(msg):
sys.stderr.write("%s: " % _('ERROR') + msg + os.linesep)
sys.exit(_("Exiting..."))
def readfile(path):
debug("Reading %s" % path)
f = open(path, 'r')
s = f.read()
f.close()
return s
def writefile(path, s):
debug("Writing %s" % path)
f = open(path, 'w')
f.write(s)
f.close()
def call(cmd, **kwargs):
"""Wrapper for subprocess.call to deal with platform-specific issues"""
if WINDOWS:
kwargs['shell'] = True
return subprocess.call(cmd, **kwargs)
def Popen(cmd, **kwargs): # pylint: disable=C0103
"""Wrapper for subprocess.Popen to deal with platform-specific issues"""
if WINDOWS:
kwargs['shell'] = True
return subprocess.Popen(cmd, **kwargs)
def gpath(*args):
"""Costruct path to file or directory in GRASS GIS installation
Can be called only after GISBASE was set.
"""
return os.path.join(GISBASE, *args)
def wxpath(*args):
"""Costruct path to file or directory in GRASS wxGUI
Can be called only after GISBASE was set.
This function does not check if the directories exist or if GUI works
this must be done by the caller if needed.
"""
global _WXPYTHON_BASE
if not _WXPYTHON_BASE:
# this can be called only after GISBASE was set
_WXPYTHON_BASE = gpath("gui", "wxpython")
return os.path.join(_WXPYTHON_BASE, *args)
# using format for most but leaving usage of template for the dynamic ones
# two different methods are easy way to implement two phase construction
HELP_TEXT = r"""GRASS GIS $VERSION_NUMBER
Geographic Resources Analysis Support System (GRASS GIS).
{usage}:
$CMD_NAME [-h | --help] [-v | --version]
[-c | -c geofile | -c EPSG:code[:datum_trans] | -c XY]
[-e] [-f] [--text | --gtext | --gui] [--config param]
[[[GISDBASE/]LOCATION/]MAPSET]
$CMD_NAME [FLAG]... GISDBASE/LOCATION/MAPSET --exec EXECUTABLE [EPARAM]...
$CMD_NAME --tmp-location [geofile | EPSG | XY] --exec EXECUTABLE [EPARAM]...
$CMD_NAME --tmp-mapset GISDBASE/LOCATION/ --exec EXECUTABLE [EPARAM]...
{flags}:
-h or --help {help_flag}
-v or --version {version_flag}
-c {create}
-e {exit_after}
-f {force_removal}
--text {text}
{text_detail}
--gtext {gtext}
{gtext_detail}
--gui {gui}
{gui_detail}
--config {config}
{config_detail}
--exec EXECUTABLE {exec_}
{exec_detail}
--tmp-location {tmp_location}
{tmp_location_detail}
--tmp-mapset {tmp_mapset}
{tmp_mapset_detail}
{params}:
GISDBASE {gisdbase}
{gisdbase_detail}
LOCATION {location}
{location_detail}
MAPSET {mapset}
GISDBASE/LOCATION/MAPSET {full_mapset}
EXECUTABLE {executable}
EPARAM {executable_params}
FLAG {standard_flags}
{env_vars}:
GRASS_GUI {gui_var}
GRASS_HTML_BROWSER {html_var}
GRASS_ADDON_PATH {addon_path_var}
GRASS_ADDON_BASE {addon_base_var}
GRASS_BATCH_JOB {batch_var}
GRASS_PYTHON {python_var}
"""
def help_message(default_gui):
t = string.Template(
HELP_TEXT.format(
usage=_("Usage"),
flags=_("Flags"),
help_flag=_("print this help message"),
version_flag=_("show version information and exit"),
create=_("create given database, location or mapset if it doesn't exist"),
exit_after=_("exit after creation of location or mapset. Only with -c flag"),
force_removal=_("force removal of .gislock if exists (use with care!). Only with --text flag"),
text=_("use text based interface (skip graphical welcome screen)"),
text_detail=_("and set as default"),
gtext=_("use text based interface (show graphical welcome screen)"),
gtext_detail=_("and set as default"),
gui=_("use $DEFAULT_GUI graphical user interface"),
gui_detail=_("and set as default"),
config=_("print GRASS configuration parameters"),
config_detail=_("options: arch,build,compiler,date,path,revision,svn_revision,version"),
params=_("Parameters"),
gisdbase=_("initial GRASS database directory"),
gisdbase_detail=_("directory containing Locations"),
location=_("initial GRASS Location"),
location_detail=_("directory containing Mapsets with one common coordinate system (projection)"),
mapset=_("initial GRASS Mapset"),
full_mapset=_("fully qualified initial Mapset directory"),
env_vars=_("Environment variables relevant for startup"),
gui_var=_("select GUI (text, gui, gtext)"),
html_var=_("set html web browser for help pages"),
addon_path_var=_("set additional path(s) to local GRASS modules or user scripts"),
addon_base_var=_("set additional GISBASE for locally installed GRASS Addons"),
batch_var=_("shell script to be processed as batch job"),
python_var=_("set Python interpreter name to override 'python'"),
exec_=_("execute GRASS module or script"),
exec_detail=_("provided executable will be executed in GRASS session"),
executable=_("GRASS module, script or any other executable"),
executable_params=_("parameters of the executable"),
standard_flags=_("standard flags"),
tmp_location=_("create temporary location (use with the --exec flag)"),
tmp_location_detail=_("created in a temporary directory and deleted at exit"),
tmp_mapset=_("create temporary mapset (use with the --exec flag)"),
tmp_mapset_detail=_("created in the specified location and deleted at exit"),
)
)
s = t.substitute(CMD_NAME=CMD_NAME, DEFAULT_GUI=default_gui,
VERSION_NUMBER=GRASS_VERSION)
sys.stderr.write(s)
def get_grass_config_dir():
"""Get configuration directory
Determines path of GRASS GIS user configuration directory and creates
it if it does not exist.
Configuration directory is for example used for grass env file
(the one which caries mapset settings from session to session).
"""
if sys.platform == 'win32':
grass_config_dirname = "GRASS7"
win_conf_path = os.getenv('APPDATA')
# this can happen with some strange settings
if not win_conf_path:
fatal(_("The APPDATA variable is not set, ask your operating"
" system support"))
if not os.path.exists(win_conf_path):
fatal(_("The APPDATA variable points to directory which does"
" not exist, ask your operating system support"))
directory = os.path.join(win_conf_path, grass_config_dirname)
else:
grass_config_dirname = ".grass7"
directory = os.path.join(os.getenv('HOME'), grass_config_dirname)
if not os.path.isdir(directory) :
try:
os.mkdir(directory)
except OSError as e:
# Can happen as a race condition
if not e.errno == errno.EEXIST or not os.path.isdir(directory):
fatal(
_("Failed to create configuration directory '%s' with error: %s")
% (directory, e.strerror))
return directory
def create_tmp(user, gis_lock):
"""Create temporary directory
:param user: user name to be used in the directory name
:param gis_lock: session lock filename to be used in the directory name
"""
# use $TMPDIR if it exists, then $TEMP, otherwise /tmp
tmp = os.getenv('TMPDIR')
if not tmp:
tmp = os.getenv('TEMP')
if not tmp:
tmp = os.getenv('TMP')
if not tmp:
tmp = tempfile.gettempdir()
if tmp:
tmpdir = os.path.join(
tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
'lock': gis_lock})
try:
os.mkdir(tmpdir, 0o700)
except:
tmp = None
if not tmp:
for ttmp in ("/tmp", "/var/tmp", "/usr/tmp"):
tmp = ttmp
tmpdir = os.path.join(
tmp, "grass7-%(user)s-%(lock)s" % {'user': user,
'lock': gis_lock})
try:
os.mkdir(tmpdir, 0o700)
except:
tmp = None
if tmp:
break
if not tmp:
fatal(_("Unable to create temporary directory <grass7-%(user)s-"
"%(lock)s>! Exiting.") % {'user': user, 'lock': gis_lock})
# promoting the variable even if it was not defined before
os.environ['TMPDIR'] = tmpdir
debug("Tmp directory '{tmpdir}' created for user '{user}'".format(
tmpdir=tmpdir, user=user))
return tmpdir
def get_gisrc_from_config_dir(grass_config_dir, batch_job):
"""Set the global grassrc file (aka grassrcrc)"""
if batch_job:
# use individual GISRCRC files when in batch mode (r33174)
filename = os.path.join(grass_config_dir, "rc.%s" % platform.node())
if os.access(filename, os.R_OK):
return filename
# use standard file if in normal mode or the special file is not available
return os.path.join(grass_config_dir, "rc")
def create_gisrc(tmpdir, gisrcrc):
# Set the session grassrc file
gisrc = os.path.join(tmpdir, "gisrc")
os.environ['GISRC'] = gisrc
# remove invalid GISRC file to avoid disturbing error messages:
try:
s = readfile(gisrcrc)
if "UNKNOWN" in s:
try_remove(gisrcrc)
s = None
except:
s = None
# Copy the global grassrc file to the session grassrc file
if s:
writefile(gisrc, s)
return gisrc
def read_gisrc(filename):
kv = {}
try:
f = open(filename, 'r')
except IOError:
return kv
for line in f:
try:
k, v = line.split(':', 1)
except ValueError as e:
warning(_("Invalid line in RC file ({file}):"
" '{line}' ({error})\n").format(
line=line, error=e, file=filename))
continue
kv[k.strip()] = v.strip()
if not kv:
warning(_("Empty RC file ({file})").format(file=filename))
f.close()
return kv
def read_env_file(path):
kv = {}
f = open(path, 'r')
for line in f:
k, v = line.split(':', 1)
kv[k.strip()] = v.strip()
f.close()
return kv
def write_gisrc(kv, filename):
f = open(filename, 'w')
for k, v in kv.items():
f.write("%s: %s\n" % (k, v))
f.close()
def read_gui(gisrc, default_gui):
grass_gui = None
# At this point the GRASS user interface variable has been set from the
# command line, been set from an external environment variable,
# or is not set. So we check if it is not set
# Check for a reference to the GRASS user interface in the grassrc file
if os.access(gisrc, os.R_OK):
kv = read_gisrc(gisrc)
if 'GRASS_GUI' in os.environ:
grass_gui = os.environ['GRASS_GUI']
elif 'GUI' in kv:
grass_gui = kv['GUI']
elif 'GRASS_GUI' in kv:
# For backward compatibility (GRASS_GUI renamed to GUI)
grass_gui = kv['GRASS_GUI']
else:
# Set the GRASS user interface to the default if needed
grass_gui = default_gui
if not grass_gui:
grass_gui = default_gui
if grass_gui == 'gui':
grass_gui = default_gui
# FIXME oldtcltk, gis.m, d.m no longer exist (remove this around 7.2)
if grass_gui in ['d.m', 'gis.m', 'oldtcltk', 'tcltk']:
warning(_("GUI <%s> not supported in this version") % grass_gui)
grass_gui = default_gui
return grass_gui
def path_prepend(directory, var):
path = os.getenv(var)
if path:
path = directory + os.pathsep + path
else:
path = directory
os.environ[var] = path
def path_append(directory, var):
path = os.getenv(var)
if path:
path = path + os.pathsep + directory
else:
path = directory
os.environ[var] = path
def set_paths(grass_config_dir):
# addons (path)
addon_path = os.getenv('GRASS_ADDON_PATH')
if addon_path:
for path in addon_path.split(os.pathsep):
path_prepend(addon_path, 'PATH')
# addons (base)
addon_base = os.getenv('GRASS_ADDON_BASE')
if not addon_base:
addon_base = os.path.join(grass_config_dir, 'addons')
os.environ['GRASS_ADDON_BASE'] = addon_base
if not WINDOWS:
path_prepend(os.path.join(addon_base, 'scripts'), 'PATH')
path_prepend(os.path.join(addon_base, 'bin'), 'PATH')
# standard installation
if not WINDOWS:
path_prepend(gpath('scripts'), 'PATH')
path_prepend(gpath('bin'), 'PATH')
# Set PYTHONPATH to find GRASS Python modules
if os.path.exists(gpath('etc', 'python')):
pythonpath = gpath('etc', 'python')
path_prepend(pythonpath, 'PYTHONPATH')
# the env var PYTHONPATH is only evaluated when python is started,
# thus:
sys.path.append(pythonpath)
# now we can import stuff from GRASS lib/python
# set path for the GRASS man pages
grass_man_path = gpath('docs', 'man')
addons_man_path = os.path.join(addon_base, 'docs', 'man')
man_path = os.getenv('MANPATH')
sys_man_path = None
if man_path:
path_prepend(addons_man_path, 'MANPATH')
path_prepend(grass_man_path, 'MANPATH')
else:
try:
nul = open(os.devnull, 'w')
p = Popen(['manpath'], stdout=subprocess.PIPE, stderr=nul)
nul.close()
s = p.stdout.read()
p.wait()
sys_man_path = s.strip()
except:
pass
if sys_man_path:
os.environ['MANPATH'] = to_text_string(sys_man_path)
path_prepend(addons_man_path, 'MANPATH')
path_prepend(grass_man_path, 'MANPATH')
else:
os.environ['MANPATH'] = to_text_string(addons_man_path)
path_prepend(grass_man_path, 'MANPATH')
# Set LD_LIBRARY_PATH (etc) to find GRASS shared libraries
# this works for subprocesses but won't affect the current process
path_prepend(gpath("lib"), LD_LIBRARY_PATH_VAR)
def find_exe(pgm):
for directory in os.getenv('PATH').split(os.pathsep):
path = os.path.join(directory, pgm)
if os.access(path, os.X_OK):
return path
return None
def set_defaults():
# GRASS_PAGER
if not os.getenv('GRASS_PAGER'):
if find_exe("more"):
pager = "more"
elif find_exe("less"):
pager = "less"
elif WINDOWS:
pager = "more"
else:
pager = "cat"
os.environ['GRASS_PAGER'] = pager
# GRASS_PYTHON
if not os.getenv('GRASS_PYTHON'):
if WINDOWS:
os.environ['GRASS_PYTHON'] = "python3.exe"
else:
os.environ['GRASS_PYTHON'] = "python3"
# GRASS_GNUPLOT
if not os.getenv('GRASS_GNUPLOT'):
os.environ['GRASS_GNUPLOT'] = "gnuplot -persist"
# GRASS_PROJSHARE
if not os.getenv('GRASS_PROJSHARE'):
os.environ['GRASS_PROJSHARE'] = CONFIG_PROJSHARE
def set_display_defaults():
""" Predefine monitor size for certain architectures"""
if os.getenv('HOSTTYPE') == 'arm':
# small monitor on ARM (iPAQ, zaurus... etc)
os.environ['GRASS_RENDER_HEIGHT'] = "320"
os.environ['GRASS_RENDER_WIDTH'] = "240"
def set_browser():
# GRASS_HTML_BROWSER
browser = os.getenv('GRASS_HTML_BROWSER')
if not browser:
if MACOSX:
# OSX doesn't execute browsers from the shell PATH - route through a
# script
browser = gpath('etc', "html_browser_mac.sh")
os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b com.apple.helpviewer"
if WINDOWS:
browser = "start"
elif CYGWIN:
browser = "explorer"
else:
# the usual suspects
browsers = ["xdg-open", "x-www-browser", "htmlview", "konqueror", "mozilla",
"mozilla-firefox", "firefox", "iceweasel", "opera", "google-chrome",
"chromium", "netscape", "dillo", "lynx", "links", "w3c"]
for b in browsers:
if find_exe(b):
browser = b
break
elif MACOSX:
# OSX doesn't execute browsers from the shell PATH - route through a
# script
os.environ['GRASS_HTML_BROWSER_MACOSX'] = "-b %s" % browser
browser = gpath('etc', "html_browser_mac.sh")
if not browser:
# even so we set to 'xdg-open' as a generic fallback
browser = "xdg-open"
os.environ['GRASS_HTML_BROWSER'] = browser
def ensure_home():
"""Set HOME if not set on MS Windows"""
if WINDOWS and not os.getenv('HOME'):
os.environ['HOME'] = os.path.join(os.getenv('HOMEDRIVE'),
os.getenv('HOMEPATH'))
def create_initial_gisrc(filename):
# for convenience, define GISDBASE as pwd:
s = r"""GISDBASE: %s
LOCATION_NAME: <UNKNOWN>
MAPSET: <UNKNOWN>
""" % os.getcwd()
writefile(filename, s)
def check_gui(expected_gui):
grass_gui = expected_gui
# Check if we are running X windows by checking the DISPLAY variable
if os.getenv('DISPLAY') or WINDOWS or MACOSX:
# Check if python is working properly
if expected_gui in ('wxpython', 'gtext'):
nul = open(os.devnull, 'w')
p = Popen([os.environ['GRASS_PYTHON']], stdin=subprocess.PIPE,
stdout=nul, stderr=nul)
nul.close()
p.stdin.write("variable=True".encode(ENCODING))
p.stdin.close()
p.wait()
msg = None
if p.returncode != 0:
# Python was not found - switch to text interface mode
msg = _("The python command does not work as expected!\n"
"Please check your GRASS_PYTHON environment variable.\n"
"Use the -help option for details.\n")
if not os.path.exists(wxpath("wxgui.py")):
msg = _("GRASS GUI not found. Please check your installation.")
if msg:
warning(_("{}\nSwitching to text based interface mode.\n\n"
"Hit RETURN to continue.\n").format(msg))
sys.stdin.readline()
grass_gui = 'text'
else:
# Display a message if a graphical interface was expected
if expected_gui != 'text':
# Set the interface mode to text
warning(_("It appears that the X Windows system is not active.\n"
"A graphical based user interface is not supported.\n"
"(DISPLAY variable is not set.)\n"
"Switching to text based interface mode.\n\n"
"Hit RETURN to continue.\n"))
sys.stdin.readline()
grass_gui = 'text'
return grass_gui
def save_gui(gisrc, grass_gui):
"""Save the user interface variable in the grassrc file"""
if os.access(gisrc, os.F_OK):
kv = read_gisrc(gisrc)
kv['GUI'] = grass_gui
write_gisrc(kv, gisrc)
def create_location(gisdbase, location, geostring):
"""Create GRASS Location using georeferenced file or EPSG
EPSG code format is ``EPSG:code`` or ``EPSG:code:datum_trans``.
:param gisdbase: Path to GRASS GIS database directory
:param location: name of new Location
:param geostring: path to a georeferenced file or EPSG code
"""
if gpath('etc', 'python') not in sys.path:
sys.path.append(gpath('etc', 'python'))
from grass.script import core as gcore # pylint: disable=E0611
try:
if geostring and geostring.upper().find('EPSG:') > -1:
# create location using EPSG code
epsg = geostring.split(':', 1)[1]
if ':' in epsg:
epsg, datum_trans = epsg.split(':', 1)
else:
datum_trans = None
gcore.create_location(gisdbase, location,
epsg=epsg, datum_trans=datum_trans)
elif geostring == 'XY':
# create an XY location
gcore.create_location(gisdbase, location)
else:
# create location using georeferenced file
gcore.create_location(gisdbase, location,
filename=geostring)
except gcore.ScriptError as err:
fatal(err.value.strip('"').strip("'").replace('\\n', os.linesep))
# TODO: distinguish between valid for getting maps and usable as current
# https://lists.osgeo.org/pipermail/grass-dev/2016-September/082317.html
# interface created according to the current usage
def is_mapset_valid(full_mapset):
"""Return True if GRASS Mapset is valid"""
# WIND is created from DEFAULT_WIND by `g.region -d` and functions
# or modules which create a new mapset. Most modules will fail if
# WIND doesn't exist (assuming that neither GRASS_REGION nor
# WIND_OVERRIDE environmental variables are set).
return os.access(os.path.join(full_mapset, "WIND"), os.R_OK)
def is_location_valid(gisdbase, location):
"""Return True if GRASS Location is valid
:param gisdbase: Path to GRASS GIS database directory
:param location: name of a Location
"""
# DEFAULT_WIND file should not be required until you do something
# that actually uses them. The check is just a heuristic; a directory
# containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
# location, while a directory lacking it probably isn't.
return os.access(os.path.join(gisdbase, location,
"PERMANENT", "DEFAULT_WIND"), os.F_OK)
# basically checking location, possibly split into two functions
# (mapset one can call location one)
def get_mapset_invalid_reason(gisdbase, location, mapset):
"""Returns a message describing what is wrong with the Mapset
The goal is to provide the most suitable error message
(rather than to do a quick check).
:param gisdbase: Path to GRASS GIS database directory
:param location: name of a Location
:param mapset: name of a Mapset
:returns: translated message
"""
full_location = os.path.join(gisdbase, location)
full_mapset = os.path.join(full_location, mapset)
# first checking the location validity
# perhaps a special set of checks with different messages mentioning mapset
# will be needed instead of the same set of messages used for location
location_msg = get_location_invalid_reason(
gisdbase, location, none_for_no_reason=True
)
if location_msg:
return location_msg
# if location is valid, check mapset
elif mapset not in os.listdir(full_location):
return _("Mapset <{mapset}> doesn't exist in GRASS Location <{loc}>. "
"A new mapset can be created by '-c' switch.").format(
mapset=mapset, loc=location)
elif not os.path.isdir(full_mapset):
return _("<%s> is not a GRASS Mapset"
" because it is not a directory") % mapset
elif not os.path.isfile(os.path.join(full_mapset, 'WIND')):
return _("<%s> is not a valid GRASS Mapset"
" because it does not have a WIND file") % mapset
# based on the is_mapset_valid() function
elif not os.access(os.path.join(full_mapset, "WIND"), os.R_OK):
return _("<%s> is not a valid GRASS Mapset"
" because its WIND file is not readable") % mapset
else:
return _("Mapset <{mapset}> or Location <{location}> is"
" invalid for an unknown reason").format(
mapset=mapset, location=location)
def get_location_invalid_reason(gisdbase, location, none_for_no_reason=False):
"""Returns a message describing what is wrong with the Location
The goal is to provide the most suitable error message
(rather than to do a quick check).
By default, when no reason is found, a message about unknown reason is
returned. This applies also to the case when this function is called on
a valid location (e.g. as a part of larger investigation).
``none_for_no_reason=True`` allows the function to be used as part of other
diagnostic. When this function fails to find reason for invalidity, other
the caller can continue the investigation in their context.
:param gisdbase: Path to GRASS GIS database directory
:param location: name of a Location
:param none_for_no_reason: When True, return None when reason is unknown
:returns: translated message or None
"""
full_location = os.path.join(gisdbase, location)
full_permanent = os.path.join(full_location, 'PERMANENT')
# directory
if not os.path.exists(full_location):
return _("Location <%s> doesn't exist") % full_location
# permament mapset
elif 'PERMANENT' not in os.listdir(full_location):
return _("<%s> is not a valid GRASS Location"
" because PERMANENT Mapset is missing") % full_location
elif not os.path.isdir(full_permanent):
return _("<%s> is not a valid GRASS Location"
" because PERMANENT is not a directory") % full_location
# partially based on the is_location_valid() function
elif not os.path.isfile(os.path.join(full_permanent,
'DEFAULT_WIND')):
return _("<%s> is not a valid GRASS Location"
" because PERMANENT Mapset does not have a DEFAULT_WIND file"
" (default computational region)") % full_location
# no reason for invalidity found (might be valid)
if none_for_no_reason:
return None
else:
return _("Location <{location}> is"
" invalid for an unknown reason").format(location=full_location)
def dir_contains_location(path):
"""Return True if directory *path* contains a valid location"""
if not os.path.isdir(path):
return False
for name in os.listdir(path):
if os.path.isdir(os.path.join(path, name)):
if is_location_valid(path, name):
return True
return False
def get_location_invalid_suggestion(gisdbase, location_name):
"""Return suggestion what to do when specified location is not valid
It gives suggestion when:
* A mapset was specified instead of a location.
* A GRASS database was specified instead of a location.
"""
full_path = os.path.join(gisdbase, location_name)
# a common error is to use mapset instead of location,
# if that's the case, include that info into the message
if is_mapset_valid(full_path):
return _(
"<{loc}> looks like a mapset, not a location."
" Did you mean just <{one_dir_up}>?").format(
loc=location_name, one_dir_up=gisdbase)
# confusion about what is database and what is location
elif dir_contains_location(full_path):
return _(
"It looks like <{loc}> contains locations."
" Did you mean to specify one of them?").format(
loc=location_name)
return None
def can_create_location(gisdbase, location):
"""Checks if location can be created"""
path = os.path.join(gisdbase, location)
if os.path.exists(path):
return False
return True
def cannot_create_location_reason(gisdbase, location):
"""Returns a message describing why location cannot be created
The goal is to provide the most suitable error message
(rather than to do a quick check).
:param gisdbase: Path to GRASS GIS database directory
:param location: name of a Location
:returns: translated message
"""
path = os.path.join(gisdbase, location)
if is_location_valid(gisdbase, location):
return _("Unable to create new location because"
" the location <{location}>"
" already exists.").format(**locals())
elif os.path.isfile(path):
return _("Unable to create new location <{location}> because"
" <{path}> is a file.").format(**locals())
elif os.path.isdir(path):
return _("Unable to create new location <{location}> because"
" the directory <{path}>"