This repository was archived by the owner on Feb 1, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathexecdmscript.py
More file actions
1840 lines (1563 loc) · 70.9 KB
/
Copy pathexecdmscript.py
File metadata and controls
1840 lines (1563 loc) · 70.9 KB
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
import os
import re
import sys
import time
import uuid
import errno
import types
import random
import typing
import pathlib
import warnings
import collections
try:
test_error = ModuleNotFoundError()
except NameError:
# for python <3.6, ModuleNotFound error does not exist
# https://docs.python.org/3/library/exceptions.html#ModuleNotFoundError
class ModuleNotFoundError(ImportError):
pass
try:
import DigitalMicrograph as DM
except (ModuleNotFoundError, ImportError) as e:
raise RuntimeError("This class can onle be used inside the Gatan " +
"Microscopy Suite program.")
DM = None
class DMScriptError(RuntimeError):
"""Error in executed dm-script code."""
# The doc is shown in the GMS error message. Keeping the real doc string
# makes the error message very big and fills it with completely useless
# information
#
# """This represents an error in the executed dm-script code.
#
# Parameters
# ----------
# msg : str
# The text to show
# script_origin : str
# The name of the executed script that the error occurres in
# line_in_origin : int
# The line in the executed script (the `script_origin`) where the error
# occurres
# line_in_complete : int
# The line in the compound script (including the setvars and readvars
# code)
# """
def __init__(self, msg: str, script_origin: str, line_in_origin: int,
line_in_complete: int) -> None:
"""
Parameters
----------
msg : str
The text to show
script_origin : str
The name of the executed script that the error occurres in
line_in_origin : int
The line in the executed script (the `script_origin`) where the error
occurres
line_in_complete : int
The line in the compound script (including the setvars and readvars
code)
"""
super(DMScriptError, self).__init__(msg)
self.script_origin = script_origin
self.line_in_origin = line_in_origin
self.line_in_complete = line_in_complete
self.msg = msg
def __str__(self) -> str:
"""Get the error as a a string.
Returns
-------
str
The error with (most of) the details
"""
return ("Error in dm-script code {} in line {} (line {} in complete " +
"code): {}").format(self.script_origin, self.line_in_origin,
self.line_in_complete, self.msg)
Convertable = typing.Union[int, float, bool, str, dict, list, tuple, None]
_python_dm_type_map = ({
"python": int,
"TagGroup": "Long",
"dmscript": "number",
"names": ("long", "integer", "int", "uint32", "uint16")
}, {
"python": float,
"TagGroup": "Float",
"dmscript": "number",
"names": ("float", "double", "decimal", "realnumber", "number")
}, {
"python": bool,
"TagGroup": "Boolean",
"dmscript": "number",
"names": ("bool", "boolean")
}, {
"python": str,
"TagGroup": "String",
"dmscript": "string",
"names": ("string", "text")
}, {
"python": dict,
"TagGroup": "TagGroup",
"dmscript": "TagGroup",
"names": ("TagGroup", "dict")
}, {
"python": (list, tuple),
"TagGroup": "TagGroup",
"dmscript": "TagGroup",
"names": ("TagList", "list")
}
)
Script = typing.Union[str, pathlib.PurePath, typing.Tuple[str, typing.Union[str, pathlib.PurePath]]]
def exec_dmscript(*scripts: Script,
readvars: typing.Optional[dict]=None,
setvars: typing.Optional[dict]=None,
separate_thread: typing.Optional[typing.Union[str, pathlib.PurePath, typing.Sequence[Script]]]=None,
debug: typing.Optional[bool]=False,
debug_file: typing.Optional[typing.Union[str, pathlib.PurePath]]=None):
"""Execute the `scripts` and prepare the `vars` for getting their values.
The `scripts` can either be filenames of dm-script files to execute or
scripts as strings. The type is guessed automatically. To explicitly set
the type use a tuple with either 'file' or 'script' at index 0 and the
corresponding value at index 1.
The `readvars` are the variables to read after the script has been executed.
Those variables have to be defined in the dm-script and they have to be in
the global scope, otherwise they will not be readable.
The `readvars` has to be a dict with the dm-script variable name as the key
and the variable type as the value. The type can either be a python type or
a dm-script type expression. Note that only basic types are supported.
`TagGroup` structures can be expressed by a dict. Use the `TagGroup` key as
the dict key, the value is the type that is expected at this index.
`TagList`s are the same, use a python list and set the types to the indices.
Both can be replaced with callback functions that will get the path of
keys/indices as their only parameter. If a `TagGroup` or `TagList`
strucutre is not given, it is auto-guessed. Note that this may have
problems because dm-script type definitions in `TagGroup`s are not definite
(e.g. float complex and float point are stored in the exact same way and
return the same type).
Supported types:
- int, aliases: Integer, short, long
- float, aliases: Float, Double, realnumber, number, decimal
- boolean
- string, alias: Text
- dict, alias: TagGroup
- list, alias: TagList
Note that dm-script variabels are case-insensitive. But the python
mechanism is not. This means you can use any typing as the key but you can
only get the value (on python side) with this exact typing.
Note that there are some variables that will be accessable in the dm-script
even if no `setvars` are given. Those are:
- `__file__`, string: the location of the dm-script file if the `scripts`
is a file path, otherwise it will be "<inline>", this is updated for
every included file
Example
-------
>>> prefix = "\n".join((
... "string command = \"select-image\";",
... "number preselected_image = {};".format(show_image)
... ))
>>> # those values will be accessable if they are defined in the dm-script
>>> rv = {"sel_img_start": "Integer",
... "sel_img_end": int,
... "options": str}
>>> # those values will be accessable in dm-script (and later in python)
>>> sv = {"a": 20}
>>> with exec_dmscript(prefix, filepath, readvars=rv, setvars=sv) as script:
... for k in script.synchronized_vars:
... # show the variables value
... print("Variable {} has the value {}".format(k, script[k]))
... # script[k] is equal to script.synchronized_vars[k]
Parameters
----------
scripts : str, pathlib.PurePath or tuple
The file path of the dmscript to execute or the dm-script code or a
tuple with 'file' or 'script' at index 0 and the file path or the
script code at index 1
readvars : dict, optional
The variables to read from the dm-script executed code (after the code
execution) and to allow getting the value of, the key has to be the
name in dm-script, the value is the type, note that defining `TagGroup`
and `TagList` structures is deprecated and will be removed
setvars : dict, optional
The variables to set before the code is executed (note that they must
not be declared), the key is the variable name, the value is the value,
the setvars will automatically be added to the `readvars` if there is
no conflict (setvars will not overwrite)
separate_thread: sequence or str or pathlib.PurePath, Optional
Script fragments to execute in a separate thread (thread is created in
the dm-script, not in python), this is useful for showing dialogs while
performing python operations, note that this is an executed functions
content on dm-script side so no definitions are allowed, default: None
debug : boolean, optional
If True the dm-script will not be executed but written to the
`debug_file`, this way errors in the dm-script can be debugged
debug_file : str, pathlib.PurePath or file object, optional
The file to save the dm-script to, this will be overwritten if it
exists, if not given the file is called "tmp-execdmscript.s" and will
be placed in the current working directory, default: None
Returns
-------
str
The code to append to the dm-script code
"""
return DMScriptWrapper(*scripts, readvars=readvars, setvars=setvars,
separate_thread=separate_thread,
debug=debug, debug_file=debug_file)
invalid_taggroup_key_characters = (":", "[", "]")
def convert_to_taggroup(tags: typing.Union[typing.Dict[str, Convertable],
typing.List[Convertable],
typing.Tuple[Convertable, ...]],
replace_invalid_chars: typing.Optional[typing.Union[bool, str, dict, typing.Callable[[str, str], str]]]=False,
path: typing.Optional[list]=[]) -> DM.Py_TagGroup:
"""Convert the given `tags` to a DigitalMicrograph `TagGroup`.
None values will be a 0 with a *short* datatype. Integers are saved as
*long*.
Note that this function can be used to set tags of images easily. Create
the `TagGroup` with this function, then copy the tags to the image
`TagGroup`.
DigitalMicrograph prevents from using some characters in the path keys. So
if a dict key contains one of those keys, an error is raised. The following
characters will raise a ValueError generated by this module. There may be
other currently unknown forbidden characters. Those will raise a ValueError
too containing the error message and type returned by the DigitalMicrograph
module.
The following characters are not allowed for keys (eventually not complete):
- Colon (":")
- Squared brackets ("[" and "]")
Those characters can be accessed in the
`execdmscript.invalid_taggroup_key_characters` tuple.
To automatically remove those keys the `replace_invalid_chars` parameter
can be used.
See
---
convert_from_taggroup()
invalid_taggroup_key_characters
DigitalMicrograph.Py_TagGroup.CopyTagsFrom()
Raises
------
ValueError
When the datatype of a given value is not savable or
When one of the values could not be inserted because of an error raised
by the DigitalMicrograph module or
When a key in a dict contains invalid characters
Parameters
----------
tags : dict, list or tuple
A dict, list or tuple that can contain the basic types int, float,
bool, str or None or dicts, lists or tuples of the same kind
replace_invalid_chars : False, str, dict or callable
Whether to replace invalid key characters or not, if True is given,
invalid characters will be replaced with an empty string, if a string
is given, all invalid characters will be replaced with this string, if
a dict is given, the dict has to contain the invalid character as a key,
the character will then be replaced with the value of the dict, if a
callable is given, this callback will be executed, the first parameter
will be the key, the second the invalid character that was found and
the callback has to return the complete new key without invalid
characters, default: False
path : list, optional
The path of the keys, this is for the error message only, do not
set this, default: []
Returns
-------
DM.Py_TagGroup
The tag group object
"""
if isinstance(tags, (list, tuple)):
datatype = list
iterator = enumerate(tags)
tag_group = DM.NewTagList()
else:
datatype = dict
iterator = tags.items()
tag_group = DM.NewTagGroup()
path_str = "".join(map(lambda x: " at dict/list index '{}'".format(x),
reversed(path)))
if replace_invalid_chars == True:
replace_invalid_chars = ""
for key, value in iterator:
for c in invalid_taggroup_key_characters:
if isinstance(key, str) and c in key:
if isinstance(replace_invalid_chars, str):
key = key.replace(c, replace_invalid_chars)
elif (isinstance(replace_invalid_chars, dict) and
c in replace_invalid_chars):
key = key.replace(c, str(replace_invalid_chars[c]))
elif callable(replace_invalid_chars):
key = replace_invalid_chars(key, c)
else:
raise ValueError(("There is a invalid character '{}' in " +
"the key '{}'{}.").format(c, key, path_str))
if isinstance(value, (dict, list, tuple)):
value = convert_to_taggroup(value, replace_invalid_chars, (*path, key))
if datatype == list:
tag_group.InsertTagAsTagGroup(key, value)
else:
tag_group.SetTagAsTagGroup(key, value)
elif isinstance(value, (int, float, bool, str, None)):
try:
if isinstance(value, int):
if datatype == list:
tag_group.InsertTagAsLong(key, value)
else:
tag_group.SetTagAsLong(key, value)
elif isinstance(value, float):
if datatype == list:
tag_group.InsertTagAsFloat(key, value)
else:
tag_group.SetTagAsFloat(key, value)
elif isinstance(value, bool):
if datatype == list:
tag_group.InsertTagAsBoolean(key, value)
else:
tag_group.SetTagAsBoolean(key, value)
elif isinstance(value, str):
if datatype == list:
tag_group.InsertTagAsString(key, value)
else:
tag_group.SetTagAsString(key, value)
elif value is None:
if datatype == list:
tag_group.InsertTagAsShort(key, 0)
else:
tag_group.SetTagAsShort(key, 0)
except Exception as e:
raise ValueError(("Could not add the value '{}' with key " +
"'{}'{} to the TagGroup. DigitalMicrograph " +
"raises an {} with the message '{}'.").format(
value, key, path_str,
e.__class__.__name__, str(e))) from e
else:
raise ValueError(("The type {} of the tag value of {} is not " +
"supported. Use int, float, bool, str or None " +
"instead.").format(type(value), ":".join(path)))
return tag_group
def convert_from_taggroup(taggroup: DM.Py_TagGroup) -> typing.Union[list, dict]:
"""Convert the given DigitalMicrograph `taggroup` to a dict or list.
Note that this function cannot be used to convert global tags. This can
only be used for `Py_TagGroup` objects created in the python code.
Otherwise the reference to the `TagGroup` object is somehow lost.
See
---
convert_to_taggroup()
Parameters
----------
taggroup : DigitalMicrograph.Py_TagGroup
The `TagGroup` object created in python
Returns
-------
dict, list
A dict or list representing the tag group, the type depends on the
`TagGroup.IsList()` return value
"""
tg_type = list if taggroup.IsList() else dict
tg_name = "convert_tg_{}".format(int(time.time() * 100))
# save tag group to persistent tags to pass them to dm-script
DM.GetPersistentTagGroup().SetTagAsTagGroup(tg_name, taggroup)
# copy the tag group to a local variable to sync that variable back to
# python
dm_code = "\n".join((
"TagGroup {};".format(tg_name),
"GetPersistentTagGroup().TagGroupGetTagAsTagGroup(\"{}\", {});".format(tg_name, tg_name)
))
with exec_dmscript(dm_code, readvars={tg_name: tg_type}) as script:
remove_global_tag(tg_name)
return script[tg_name]
raise RuntimeError(
("Could not find the TagGroup {} in synchronized the dm-script code " +
"that was used to convert a TagGroup to a dict or list.").format(tg_name)
)
def get_dm_type(datatype: typing.Union[str, type],
for_taggroup: typing.Optional[bool]=False):
"""Get the dm-script equivalent for the given `datatype`.
Note that not all types are supported, even if there is an equvalent in
dm-script.
Raises
------
LookupError
When the `datatype` is not known
Parameters
----------
datatype : str or type
The type to get the dm-script type of, python types and common type
expressions are supported
for_taggroup : boolean, optional
Whether the datatype should be returned so it can be used directly in
`taggroup.GetTagAs<datatype>()` function or not, default: False
Returns
-------
str
The datatype name in dm-script
"""
global _python_dm_type_map
if isinstance(datatype, str):
datatype = datatype.lower()
for type_def in _python_dm_type_map:
names = list(map(lambda x: x.lower() if isinstance(x, str) else x,
type_def["names"]))
if datatype in names or (isinstance(type_def["python"], (list, tuple)) and
datatype in type_def["python"]) or datatype == type_def["python"]:
if for_taggroup:
return type_def["TagGroup"]
else:
return type_def["dmscript"]
raise LookupError("Cannot find the dm-script type for '{}'".format(datatype))
def get_python_type(datatype: typing.Union[str, type]):
"""Get the python equivalent for the given `datatype`.
Note that not all types are supported, even if there is an equvalent in
dm-script.
Raises
------
LookupError
When the `datatype` is not known
Parameters
----------
datatype : str or type
The type to get the python type of, python types and common type
expressions are supported
Returns
-------
type
The datatype name in python
"""
global _python_dm_type_map
if isinstance(datatype, str):
datatype = datatype.lower()
for type_def in _python_dm_type_map:
names = list(map(lambda x: x.lower() if isinstance(x, str) else x,
type_def["names"]))
if datatype in names or (isinstance(type_def["python"], (list, tuple)) and
datatype in type_def["python"]) or datatype == type_def["python"]:
if isinstance(type_def["python"], (list, tuple)):
return type_def["python"][0]
else:
return type_def["python"]
raise LookupError("Cannot find the python type for '{}'".format(datatype))
_replace_dm_variable_name_reg = re.compile(r"[^\w\d_]")
def escape_dm_variable(variable_name: str):
"""Replace all special characters that are not allowed with underlines.
Raises
------
ValueError:
When the variable is not a valid name (this is only when it is an empty
string at the moment)
Parameters
----------
variable_name : str
The name of the variable
Returns
-------
str
The valid variable name
"""
global _replace_dm_variable_name_reg
name = re.sub(_replace_dm_variable_name_reg, "_", str(variable_name))
if name == "":
raise ValueError(("The variable name '{}' is not a valid (dm-script) " +
"variable name.").format(variable_name))
return name
def escape_dm_string(str_content: str):
"""Escape all special characters so the `str_content` can safely be used
in dm-script strings.
Parameters
----------
str_content : str
The text that should be added to a dm-script string
Returns
-------
str
The str with additional escape characters
"""
return (str(str_content)
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\t", "\\t")
.replace("\0", "\\0"))
def remove_global_tag(*tagname: str) -> None:
"""Remove the global tag with the given `tagname`.
Parameter
---------
tagname : str
The tag name of the global tag to remove
"""
if DM is not None:
for tgn in tagname:
DM.GetPersistentTagGroup().DeleteTagWithLabel(tgn)
def get_persistent_tag(path: typing.Optional[typing.Union[typing.Sequence[str], str, None]]=None) -> typing.Union[Convertable, typing.Dict[str, Convertable], typing.List[Convertable]]:
"""Get the value of a persistent tag.
The `path` can be the path to the value to get. This can either be a
sequence containing the indices to walk through, starting from the most
outer one (from the base persistent `TagGroup`), a string containing the
name of the tag to get or a path as a string with the colon (":") as a
separator.
The return value will be the converted tag. Each `dm-script` value will
automatically be converted to the corresponding python type. Each `TagGroup`
will be a `dict`, each `TagList` will be a `list`.
Note that only the types supported by the `DMScriptWrapper` are supported.
Those are all "base" types which are the types supported by the
`get_python_type()` function.
Raises
------
KeyError
When the given `path` does not exist
Parameters
----------
path : sequence, str or None, optional
The path of the value to get either as a sequence of strings or as a
string, use ":" as a separator, if not given the base persistent tags
will be returned, default: None
Returns
-------
int, float, bool, str, dict, or list
The parsed tag value
"""
if path is not None and not isinstance(path, str):
path = ":".join(path)
id_ = int(time.time() * 100)
value_tagname = "value_tag_{}".format(id_)
setvars = {
"path": path,
"value_tagname": value_tagname
}
readvars = {
"value_taggroup": dict,
"exists": bool
}
dmscript = "\n".join((
"number exists = GetPersistentTagGroup().TagGroupDoesTagExist(path);",
"TagGroup value_taggroup = NewTagGroup();",
"",
"if(exists){",
"TagGroup source;",
"string source_label;",
"number source_index = GetPersistentTagGroup().TagGroupParseTagPath(path, source, source_label);",
"",
"number target_index = value_taggroup.TagGroupCreateNewLabeledTag(value_tagname);",
"value_taggroup.TagGroupCopyTagToIndex(target_index, source, source_index);",
# "value_taggroup.TagGroupOpenBrowserWindow(0);"
"}"
))
with exec_dmscript(dmscript, readvars=readvars, setvars=setvars) as script:
if script["exists"] and value_tagname in script["value_taggroup"]:
return script["value_taggroup"][value_tagname]
raise KeyError(("No value was found in the persistent tags for " +
"the path '{}'.").format(path))
def unique_tag(tagname: str) -> str:
"""Get the `tagname` with an appended UUID.
Parameters
----------
tagname : str
The tagname
Returns
-------
str
A unique tagname to use
"""
return "{}_{}".format(tagname, str(uuid.uuid4()).replace("-", "_"))
class DMScriptWrapper:
"""Wraps one or more dm-scripts.
"""
_unescape_char_reg = r"\{\{unc([\d]+)\}\}"
_unescape_chars_reg = "(?:{})+".format(_unescape_char_reg)
_unescape_char_reg = re.compile(_unescape_char_reg)
_unescape_chars_reg = re.compile(_unescape_chars_reg)
debug_start_marker = "@execdmscript.ignore.start"
debug_end_marker = "@execdmscript.ignore.end"
def __init__(self,
*scripts: Script,
readvars: typing.Optional[dict]=None,
setvars: typing.Optional[dict]=None,
separate_thread: typing.Optional[typing.Union[str, pathlib.PurePath, typing.Sequence[Script]]]=None,
debug: typing.Optional[bool]=False,
debug_file: typing.Optional[typing.Union[str, pathlib.PurePath]]=None) -> None:
"""Initialize the script wrapper.
Parameters
----------
scripts : str, pathlib.PurePath or tuple
The file path of the dmscript to execute or the dm-script code or a
tuple with 'file' or 'script' at index 0 and the file path or the
script code at index 1
readvars : dict, optional
The variables to read from the dm-script executed code (after the
code execution) and to allow getting the value of, the key has to
be the name in dm-script, the value is the type, note that defining
`TagGroup` and `TagList` structures is deprecated and will be
removed
setvars : dict, optional
The variables to set before the code is executed (note that they
must not be declared), the key is the variable name, the value is
the value, the setvars will automatically be added to the
`readvars` if there is no conflict (setvars will not overwrite)
separate_thread: sequence or str or pathlib.PurePath, Optional
Script fragments to execute in a separate thread (thread is created
in the dm-script, not in python), this is useful for showing
dialogs while performing python operations, note that this is an
executed functions content on dm-script side so no definitions are
allowed, default: None
debug : boolean, optional
If True the dm-script will not be executed but written to the
`debug_file`, this way errors in the dm-script can be debugged
debug_file : str, pathlib.PurePath or file object, optional
The file to save the dm-script to, this will be overwritten if it
exists, if not given the file is called "tmp-execdmscript.s" and
will be placed in the current working directory, default: None
"""
self.scripts = DMScriptWrapper.normalizeScripts(scripts)
self._unique_id = str(uuid.uuid4()).replace("-", "_")
self.persistent_tag = "__execdmscript_{}".format(self._unique_id)
self.readvars = readvars
self.setvars = setvars
self.synchronized_vars = {}
self.separate_thread = separate_thread
if isinstance(self.separate_thread, str) and self.separate_thread != "":
# convert to sequence
self.separate_thread = (self.separate_thread, )
self.debug = bool(debug)
self.debug_file = debug_file
self._slash_split_reg = re.compile("(?<!/)/(?!/)")
self._script_sources = []
# add all setvars to the readvars to allow accessing them after the
# script is executed
if isinstance(self.setvars, dict):
if not isinstance(self.readvars, dict):
self.readvars = {}
for key, val in self.setvars.items():
if not key in self.readvars:
self.readvars[key] = type(val)
def __del__(self) -> None:
"""Desctruct the object."""
self.freeAllSyncedVars()
def __call__(self) -> bool:
"""Execute the code.
Returns
-------
bool
Success
"""
dmscript = self.getExecDMScriptCode()
if hasattr(self.debug_file, "write") and callable(self.debug_file.write):
debug_file = self.debug_file
close_debug_file = False
debug_file_name = repr(debug_file)
else:
if isinstance(self.debug_file, (str, pathlib.PurePath)):
path = self.debug_file
else:
path = os.path.join(os.getcwd(), "tmp-execdmscript.s")
try:
debug_file = open(path, "w+")
# opened the file so close it after writing
close_debug_file = True
debug_file_name = path
except Exception:
debug_file = None
close_debug_file = False
debug_file_name = None
if self.debug and debug_file is not None:
debug_file.write(dmscript)
if (close_debug_file and hasattr(debug_file, "close") and
callable(debug_file.close)):
debug_file.close()
print(("execdmscript: Did not execute script but saved to {} " +
"because file is running in debug mode.").format(debug_file_name))
return True
else:
try:
DM.ExecuteScriptString(dmscript)
except RuntimeError as e:
matches = re.match(r"Error in line ([\d]+)\s*\n(.*)", str(e))
if matches is not None:
# there is an error in the executed script, read the line
# and check in which script the error is, then calculate
# the line in the script, this is better information for
# the user as he/she doesn't know what code is prefixed
# and suffixed
line = int(matches.group(1))
for script_src in self._script_sources:
if (script_src["start"] <= line and
line <= script_src["end"]):
msg = matches.group(2)
src = script_src["origin-name"]
l = line - script_src["start"] + 1
error = DMScriptError(msg, src, l, line)
# GMS shows the docstring in their error message,
# so to offer a useful text, overwrite the docstring
error.__doc__ = str(error)
type(error).__doc__ = str(error)
DMScriptError.__doc__ = str(error)
raise error from e
else:
raise e
self._loadVariablesFromDMScript()
return True
return False
def __enter__(self) -> "DMScriptWrapper":
"""Enter the `with`-block."""
self.exec()
return self
def __exit__(self, exc_type: typing.Optional[typing.Type[BaseException]],
exc_instance: typing.Optional[BaseException],
exc_traceback: typing.Optional[types.TracebackType]) -> bool:
"""Exit the `with`-block."""
self.freeAllSyncedVars()
def __getitem__(self, var: typing.Any) -> typing.Any:
"""Get the dm script variable with the `var`."""
return self.getSyncedVar(var)
def __iter__(self) -> typing.Iterator:
"""Get the iterator to iterate over the dm-script variables."""
return self.synchronized_vars.__iter__
def __len__(self) -> int:
"""Get the number of synchronized variables."""
return len(self.synchronized_vars)
def __contains__(self, var: typing.Any) -> bool:
"""Get whether the `var` is a synchronized dm-script variable."""
return var in self.synchronized_vars
def exec(self) -> bool:
"""Execute the code.
Returns
-------
bool
Success
"""
return self()
def getExecDMScriptCode(self) -> str:
"""Get the dm-script code to execute.
The returned code contains all files, all code fragments and
the complete synchronizing mechanism.
Returns
-------
str
The code to execute
"""
self._script_sources = []
dmscript = []
startpos = 1
# write some comments
code = [
"// This code is created automatically by concatenating files and ",
"// code fragments.",
"// ",
"// This code is generated with the exedmscript module.",
"//",
"//" + " =" * 50
]
dmscript, startpos = self._addCode(
dmscript, code, "<comments>", None, startpos
)
# the code for the set variables
code = self.getSetVarsDMCode()
dmscript, startpos = self._addCode(
dmscript, code, "<setvars>", self.getSetVarsDMCode, startpos
)
# add the real code to execute
dm_file_added = False
for i, (kind, script) in enumerate(self.scripts):
if isinstance(kind, str):
kind = kind.lower()
if kind == "file":
source = script
dm__file__ = script
comment = "// File {}".format(escape_dm_string(source))
with open(script, "r") as f:
code = f.read()
elif kind == "script":
source = "<inline script in parameter {}>".format(i)
comment = "// Directly given script"
dm__file__ = "<inline>"
code = script
dmscript, startpos = self._addCode(
dmscript,
DMScriptWrapper.getDMCodeForVariable("__file__", dm__file__, not dm_file_added),
"<__file__>",
None,
startpos
)
dmscript, startpos = self._addCode(
dmscript, comment, "<comments>", None, startpos, True
)
dmscript, startpos = self._addCode(
dmscript, code, source, script, startpos, True
)
if not dm_file_added:
dm_file_added = True
wait_for_signals = []
# execute in a separate thread
if isinstance(self.separate_thread, collections.Sequence):
for i, (kind, script) in enumerate(DMScriptWrapper.normalizeScripts(self.separate_thread)):
wait_for_signals.append(i)
code = self.getSeparateThreadStartCode(i)
dmscript, startpos = self._addCode(
dmscript, code, "<prepare separate thread>",
self.getSeparateThreadStartCode, startpos
)
if isinstance(kind, str):
kind = kind.lower()
if kind == "file":
source = script
comment = "// File {}".format(escape_dm_string(source))
with open(script, "r") as f:
code = f.read()
elif kind == "script":
source = "<separate_thread parameter {}>".format(i)
comment = "// Directly given script"
code = script
code = code.encode("iso-8859-1")
dmscript, startpos = self._addCode(
dmscript, comment, "<comments>", None, startpos
)
dmscript, startpos = self._addCode(
dmscript, code, source, script, startpos
)
code = self.getSeparateThreadEndCode(i)
dmscript, startpos = self._addCode(
dmscript, code, "<prepare separate thread>",
self.getSeparateThreadEndCode, startpos
)
# for i in wait_for_signals:
# code = self.getSeparateThreadWaitCode(i)
# dmscript, startpos = self._addCode(
# dmscript, code, "<wait for signal {}>".format(i),
# self.getSeparateThreadWaitCode, startpos
# )
# execdscript used "lib"-functions
code = DMScriptWrapper._getExecdmscriptLibFunctions()
dmscript, startpos = self._addCode(
dmscript, code, "<execdmscript lib functions>",
DMScriptWrapper._getExecdmscriptLibFunctions, startpos
)
# the code for the readvars
code = self.getSyncDMCode()
dmscript, startpos = self._addCode(
dmscript, code, "<readvars>", self.getSyncDMCode, startpos
)
return "\n".join(dmscript)
def _addCode(self, dmscript: list, code: typing.Union[list, tuple, str],
origin_name: str, origin_detail: typing.Any,
startpos: typing.Optional[int]=1,
remove_debug_lines: typing.Optional[bool]=True) -> typing.Tuple[list, int]:
"""Add the `code` to the `dmscript` and save its position in
`DMScriptWrapper._script_sources`.
Raises
------
ValueError
When the `code` neither is a string nor a list nor a tuple
Parameters
----------
dmscript : list
The list of code fragments that create the dmscript
code : str, list or tuple
One or more code fragments to add to the `dmscript`
origin_name : str