-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathpy.ml
3068 lines (2497 loc) · 87.8 KB
/
py.ml
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
module Stdlib_printexc = Printexc
(* Workaround for opaque Printexc bug in Stdcompat 9 *)
open Stdcompat
type pyobject = Pytypes.pyobject
type input = Pytypes.input = Single | File | Eval
let string_of_input input =
match input with
| File -> "exec"
| Eval -> "eval"
| Single -> "single"
type 'a file = 'a Pytypes.file = Filename of string | Channel of 'a
type compare = Pytypes.compare = LT | LE | EQ | NE | GT | GE
type ucs = UCSNone | UCS2 | UCS4
type closure =
WithoutKeywords of (pyobject -> pyobject)
| WithKeywords of (pyobject -> pyobject -> pyobject)
external load_library: string option -> bool option -> unit = "py_load_library"
external is_debug_build: unit -> bool = "py_is_debug_build"
external unsetenv: string -> unit = "py_unsetenv"
external finalize_library: unit -> unit = "py_finalize_library"
external pywrap_closure: string option -> string -> closure -> pyobject
= "pyml_wrap_closure"
external pynull: unit -> pyobject = "PyNull_wrapper"
external pynone: unit -> pyobject = "PyNone_wrapper"
external pytrue: unit -> pyobject = "PyTrue_wrapper"
external pyfalse: unit -> pyobject = "PyFalse_wrapper"
external pytuple_empty: unit -> pyobject = "PyTuple_Empty_wrapper"
external pyobject_callfunctionobjargs: pyobject -> pyobject array -> pyobject
= "PyObject_CallFunctionObjArgs_wrapper"
external pyobject_callmethodobjargs: pyobject -> pyobject -> pyobject array
-> pyobject = "PyObject_CallMethodObjArgs_wrapper"
external pyerr_fetch_internal: unit -> pyobject * pyobject * pyobject
= "PyErr_Fetch_wrapper"
external pyerr_restore_internal: pyobject -> pyobject -> pyobject -> unit
= "PyErr_Restore_wrapper"
external pystring_asstringandsize: pyobject -> string option
= "PyString_AsStringAndSize_wrapper"
external pyobject_ascharbuffer: pyobject -> string option
= "PyObject_AsCharBuffer_wrapper"
external pyobject_asreadbuffer: pyobject -> string option
= "PyObject_AsReadBuffer_wrapper"
external pyobject_aswritebuffer: pyobject -> string option
= "PyObject_AsWriteBuffer_wrapper"
external pylong_fromstring: string -> int -> pyobject * int
= "PyLong_FromString_wrapper"
external pycapsule_isvalid: Pytypes.pyobject -> string -> int
= "Python27_PyCapsule_IsValid_wrapper"
external pycapsule_check: Pytypes.pyobject -> int
= "pyml_capsule_check"
external pyframe_new : string -> string -> int -> Pytypes.pyobject
= "pyml_pyframe_new"
external ucs: unit -> ucs = "py_get_UCS"
(* Avoid warning 32. *)
let () = ignore (UCSNone, UCS2, UCS4)
let initialized = ref false
let is_initialized () = !initialized
let assert_initialized () =
if not !initialized then
failwith "Py.assert_initialized: run 'Py.initialize ()' first"
let version_value = ref ""
let version_major_value = ref 0
let version_minor_value = ref 0
let program_name = ref Sys.argv.(0)
let set_program_name s =
program_name := s;
if !initialized then
if !version_major_value <= 2 then
Pywrappers.Python2.py_setprogramname s
else
Pywrappers.Python3.py_setprogramname s
let python_home = ref None
let pythonpaths = ref []
let set_python_home s =
python_home := (Some s);
if !initialized then
if !version_major_value <= 2 then
Pywrappers.Python2.py_setpythonhome s
else
Pywrappers.Python3.py_setpythonhome s
let add_python_path path =
pythonpaths := path :: !pythonpaths
let extract_version version_line =
let before =
try String.index version_line ' '
with Not_found ->
let msg =
Printf.sprintf "Py.extract_version: cannot parse the version line '%s'"
version_line in
failwith msg in
Pyutils.split_left_on_char ~from:(succ before) ' ' version_line
let extract_version_major_minor version =
try
if String.length version >= 3 && version.[1] = '.' then
let major = int_of_string (String.sub version 0 1) in
let minor =
if String.length version = 3 || version.[3] = '.' then
int_of_string (String.sub version 2 1)
else if String.length version >= 5 && version.[4] = '.' then
int_of_string (String.sub version 2 2)
else
raise Exit in
(major, minor)
else
raise Exit
with Exit | Failure _ ->
let msg =
Printf.sprintf
"Py.extract_version_major_minor:\
unable to parse the version number '%s'"
version in
failwith msg
let run_command ?(input = "") command read_stderr =
let (input_channel, output, error) =
Unix.open_process_full command (Unix.environment ()) in
let result =
try
output_string output input;
close_out output;
Pyutils.input_lines (if read_stderr then error else input_channel)
with _ ->
begin
try
ignore (Unix.close_process_full (input_channel, output, error))
with _ ->
()
end;
let msg =
Printf.sprintf "Py.run_command: unable to read the result of '%s'"
command in
failwith msg in
if Unix.close_process_full
(input_channel, output, error) <> Unix.WEXITED 0 then
begin
let msg = Printf.sprintf "Py.run_command: unable to run '%s'" command in
failwith msg;
end;
result
let run_command_opt ?input command read_stderr =
try Some (run_command ?input command read_stderr)
with Failure _ -> None
let parent_dir filename =
let dirname = Filename.dirname filename in
Filename.concat dirname Filename.parent_dir_name
let has_putenv = ref false
let has_set_pythonpath = ref None
let init_pythonhome verbose pythonhome =
pythonhome <> "" &&
try
ignore (Sys.getenv "PYTHONHOME");
false
with Not_found ->
if verbose then
begin
Printf.eprintf "Temporary set PYTHONHOME=\"%s\".\n" pythonhome;
flush stderr;
end;
Unix.putenv "PYTHONHOME" pythonhome;
has_putenv := true;
true
let uninit_pythonhome () =
if !has_putenv then
begin
unsetenv "PYTHONHOME";
has_putenv := false
end
let uninit_pythonpath () =
match !has_set_pythonpath with
None -> ()
| Some old_pythonpath ->
begin
has_set_pythonpath := None;
match old_pythonpath with
None -> unsetenv "PYTHONPATH"
| Some old_pythonpath' -> Unix.putenv "PYTHONPATH" old_pythonpath'
end
let ldd executable =
let command =
match Pyml_arch.os with
| Pyml_arch.Mac -> Printf.sprintf "otool -L %s" executable
| _ -> Printf.sprintf "ldd %s" executable in
match run_command_opt command false with
None -> []
| Some lines ->
let extract_line line =
String.trim
(Pyutils.split_left_on_char '('
(Pyutils.split_right_on_char '>' line)) in
List.map extract_line lines
let ldconfig () =
match run_command_opt "ldconfig -p" false with
None -> []
| Some lines ->
let extract_line line =
String.trim (Pyutils.split_right_on_char '>' line) in
List.map extract_line lines
let libpython_from_interpreter python_full_path =
let lines = ldd python_full_path in
let is_libpython line =
let basename = Filename.basename line in
Stdcompat.String.starts_with ~prefix:"libpython" basename in
List.find_opt is_libpython lines
let libpython_from_ldconfig major minor =
let lines = ldconfig () in
let prefix =
match major, minor with
None, _ -> "libpython"
| Some major', None -> Printf.sprintf "libpython%d" major'
| Some major', Some minor' ->
Printf.sprintf "libpython%d.%d" major' minor' in
let is_libpython line =
let basename = Filename.basename line in
Stdcompat.String.starts_with ~prefix:prefix basename in
List.find_opt is_libpython lines
let parse_python_list list =
let length = String.length list in
let buffer = Buffer.create 17 in
let rec parse_item accu index =
if index < length then
match list.[index] with
'\'' ->
begin
let item = Buffer.contents buffer in
let accu = item :: accu in
if index + 1 < length then
match list.[index + 1] with
']' ->
if index + 2 = length then
Some (List.rev accu)
else
None
| ',' ->
if list.[index + 2] = ' ' && list.[index + 3] = '\'' then
begin
Buffer.clear buffer;
parse_item accu (index + 4)
end
else
None
| _ ->
None
else
None
end
| '\\' ->
if index + 1 < length then
begin
match list.[index + 1] with
'\n' -> parse_item accu (index + 2)
| '0' .. '9' ->
if index + 3 < length then
begin
let octal_number = String.sub list (index + 1) 3 in
let c = char_of_int (Pyutils.int_of_octal octal_number) in
Buffer.add_char buffer c;
parse_item accu (index + 4)
end
else
None
| 'x' ->
if index + 2 < length then
begin
let hexa_number = String.sub list (index + 1) 2 in
let c = char_of_int (Pyutils.int_of_hex hexa_number) in
Buffer.add_char buffer c;
parse_item accu (index + 3)
end
else
None
| c ->
begin
match
try
let c' =
match c with
'\\' -> '\\'
| '\'' -> '\''
| '"' -> '"'
| 'a' -> '\007'
| 'b' -> '\b'
| 'f' -> '\012'
| 'n' -> '\n'
| 'r' -> '\r'
| 't' -> '\t'
| 'v' -> '\011'
| _ -> raise Not_found in
Some c'
with Not_found -> None
with
None -> None
| Some c' ->
Buffer.add_char buffer c';
parse_item accu (index + 2)
end
end
else
None
| c ->
Buffer.add_char buffer c;
parse_item accu (index + 1)
else
None in
if length >= 2 && list.[0] == '[' then
match list.[1] with
'\'' ->
Buffer.clear buffer;
parse_item [] 2
| ']' when length = 2 -> Some []
| _ -> None
else
None
let pythonpaths_from_interpreter python_full_path =
let command = "\
import sys
print(sys.path)
" in
match
try run_command ~input:command python_full_path false
with Failure _ -> []
with
[path_line] ->
begin
match parse_python_list path_line with
None -> []
| Some paths -> paths
end
| _ -> []
let concat_library_filenames library_paths library_filenames =
let expand_filepaths filename =
filename ::
List.map (fun path -> Filename.concat path filename) library_paths in
List.concat (List.map expand_filepaths library_filenames)
let library_suffix =
match Pyml_arch.os with
| Pyml_arch.Mac -> ".dylib"
| _ -> ".so"
let libpython_from_pkg_config version_major version_minor =
let command =
Printf.sprintf "pkg-config --libs python-%d.%d" version_major
version_minor in
match run_command_opt command false with
Some (words :: _) ->
let word_list = String.split_on_char ' ' words in
let unable_to_parse () =
let msg = Printf.sprintf
"Py.find_library_path: unable to parse the output of pkg-config '%s'"
words in
failwith msg in
let parse_word (library_paths, library_filename) word =
if String.length word > 2 then
match String.sub word 0 2 with
"-L" ->
let word' =
Pyutils.substring_between word 2 (String.length word) in
(word' :: library_paths, library_filename)
| "-l" ->
let word' =
Pyutils.substring_between word 2 (String.length word) in
if library_filename <> None then
unable_to_parse ();
let library_filename =
Printf.sprintf "lib%s%s" word' library_suffix in
(library_paths, Some library_filename)
| _ -> (library_paths, library_filename)
else (library_paths, library_filename) in
let (library_paths, library_filename) =
List.fold_left parse_word ([], None) word_list in
let library_filename =
match library_filename with
None -> unable_to_parse ()
| Some library_filename -> library_filename in
Some (concat_library_filenames library_paths [library_filename])
| _ -> None
let library_patterns : (int -> int -> string) list =
match Pyml_arch.os with
| Pyml_arch.Windows ->
[Printf.sprintf "python%d%dm.dll"; Printf.sprintf "python%d%d.dll"]
| Pyml_arch.Mac ->
[Printf.sprintf "libpython%d.%dm.dylib";
Printf.sprintf "libpython%d.%d.dylib"]
| Pyml_arch.Unix ->
[Printf.sprintf "libpython%d.%dm.so";
Printf.sprintf "libpython%d.%d.so"]
let library_filenames_from_paths version_major version_minor paths =
let library_filenames =
List.map
(fun format -> format version_major version_minor)
library_patterns in
concat_library_filenames paths library_filenames
let libpython_from_python_config version_major version_minor =
let command =
Printf.sprintf "python%d.%d-config --ldflags" version_major version_minor in
match run_command_opt command false with
| Some (words :: _) ->
let word_list = String.split_on_char ' ' words in
let parse_word library_paths word =
if String.length word > 2 then
match String.sub word 0 2 with
"-L" ->
let word' =
Pyutils.substring_between word 2 (String.length word) in
word' :: library_paths
| _ -> library_paths
else library_paths in
let library_paths =
List.fold_left parse_word [] word_list in
Some (library_filenames_from_paths version_major version_minor library_paths)
| _ -> None
let libpython_from_python_config_prefix version_major version_minor =
let command =
Printf.sprintf "python%d.%d-config --prefix" version_major version_minor in
match run_command_opt command false with
| Some (prefix :: _) ->
let library_paths = [Filename.concat prefix "lib"] in
Some (library_filenames_from_paths version_major version_minor library_paths)
| _ -> None
let getenv_opt var =
try Some (Sys.getenv var)
with Not_found -> None
let libpython_from_pythonhome version_major version_minor python_full_path =
let library_paths =
match
match getenv_opt "PYTHONHOME" with
| Some python_home -> Some (Pyutils.split_left_on_char ':' python_home)
| None ->
match python_full_path with
| Some python_full_path -> Some (parent_dir python_full_path)
| None -> None
with
None -> failwith "Unable to find libpython!"
| Some dir ->
[Filename.concat dir "lib"] in
library_filenames_from_paths version_major version_minor library_paths
let libpython_from_pythonpath version_major version_minor =
match getenv_opt "PYTHONPATH" with
| None -> None
| Some pythonpath ->
let paths = String.split_on_char ':' pythonpath in
let python_zip = Printf.sprintf "python%d%d.zip" version_major version_minor in
let is_python_zip filename =
Filename.basename filename = python_zip in
match List.find_opt is_python_zip paths with
| None -> None
| Some filename ->
let dir = Filename.dirname filename in
Some (library_filenames_from_paths version_major version_minor [dir])
let find_library_path version_major version_minor python_full_path =
let heuristics = [
(fun () ->
Option.bind python_full_path (fun path ->
Option.map (fun path -> [path]) (libpython_from_interpreter path)));
(fun () ->
Option.map (fun path -> [path])
(libpython_from_ldconfig version_major version_minor));
(fun () ->
Option.bind version_major (fun version_major ->
Option.bind version_minor (fun version_minor ->
libpython_from_pkg_config version_major version_minor)));
(fun () ->
Option.bind version_major (fun version_major ->
Option.bind version_minor (fun version_minor ->
libpython_from_python_config_prefix version_major version_minor)));
(fun () ->
Option.bind version_major (fun version_major ->
Option.bind version_minor (fun version_minor ->
libpython_from_python_config version_major version_minor)));
(fun () ->
Option.bind version_major (fun version_major ->
Option.bind version_minor (fun version_minor ->
Some (libpython_from_pythonhome version_major version_minor
python_full_path))));
(fun () ->
Option.bind version_major (fun version_major ->
Option.bind version_minor (fun version_minor ->
libpython_from_pythonpath version_major version_minor)));
] in
List.concat (List.map (fun f -> Option.value ~default:[] (f ())) heuristics)
let python_version_from_interpreter interpreter =
let version_line =
let python_version_cmd = Printf.sprintf "\"%s\" --version" interpreter in
try List.hd (run_command python_version_cmd false)
with Failure _ -> List.hd (run_command python_version_cmd true) in
extract_version version_line
let library_filename = ref None
let load_library filename =
library_filename := filename;
load_library filename None
let get_library_filename () = !library_filename
let find_library ~verbose ~version_major ~version_minor ~debug_build:_
python_full_path =
try
load_library None
with Failure _ ->
let library_filenames =
find_library_path version_major version_minor python_full_path in
let errors = Buffer.create 17 in
let rec try_load_library library_filenames =
match library_filenames with
[] ->
let msg =
Printf.sprintf
"Py.find_library: unable to find the Python library%s"
(Buffer.contents errors) in
failwith msg
| filename :: others ->
begin
(*
let pythonhome_set =
not (Filename.is_implicit filename) &&
init_pythonhome verbose (parent_dir filename) in
*)
try
if verbose then
begin
Printf.eprintf "Trying to load \"%s\".\n" filename;
flush stderr;
end;
load_library (Some filename);
with Failure msg ->
(*
if pythonhome_set then
uninit_pythonhome ();
*)
if verbose then
begin
Printf.eprintf "Failed: \"%s\".\n" msg;
flush stderr;
end;
Printf.bprintf errors " [%s returned %s]" filename msg;
try_load_library others
end in
try_load_library library_filenames
let initialize_library ~verbose ~version_major ~version_minor
~debug_build python_full_path =
begin
match !python_home with
None -> ()
| Some s -> ignore (init_pythonhome verbose s)
end;
find_library ~verbose ~version_major ~version_minor ~debug_build
python_full_path;
(*
begin
match python_full_path with
None -> ()
| Some python_full_path' ->
let pythonhome =
let dirname = Filename.dirname python_full_path' in
if Filename.basename dirname = "bin" then
Filename.concat dirname Filename.parent_dir_name
else
dirname in
ignore (init_pythonhome verbose pythonhome);
end;
*)
set_program_name !program_name;
begin
match !python_home with
None -> ()
| Some s -> set_python_home s
end
let get_version = Pywrappers.py_getversion
let which_command =
match Pyml_arch.os with
| Pyml_arch.Windows -> "where"
| _ -> "command -v"
let which program =
let exe =
match Pyml_arch.os with
| Pyml_arch.Windows ->
if Filename.check_suffix program ".exe" then
program
else
program ^ ".exe"
| _ -> program in
let command = Printf.sprintf "%s \"%s\"" which_command exe in
match run_command_opt command false with
Some (path :: _) -> Some path
| _ -> None
let find_interpreter interpreter version minor =
match interpreter with
Some interpreter' ->
if String.contains interpreter' '/' then
Some interpreter'
else
which interpreter'
| None ->
match
Option.bind version
(fun version' ->
match
Option.bind minor
(fun minor' ->
which (Printf.sprintf "python%d.%d" version' minor'))
with
| Some result -> Some result
| None -> which (Printf.sprintf "python%d" version'))
with
| Some result -> Some result
| None ->
match which "python" with
| Some result -> Some result
| None ->
match which "python3" with
| Some result -> Some result
| None -> None
let version_mismatch interpreter found expected =
Printf.sprintf
"Version mismatch: %s is version %s but version %s is expected"
interpreter found expected
let build_version_string major minor =
Printf.sprintf "%d.%d" major minor
let path_separator =
match Pyml_arch.os with
| Pyml_arch.Windows -> ";"
| _ -> ":"
(* Preserve signal behavior for sigint (Ctrl+C)
(Reported by Arulselvan Madhavan,
see https://github.com/thierry-martinez/pyml/issues/83)
pythonlib changes the handling of sigint, making programs
uninterruptible when the library is loaded.
The following function restores sigint handling and `initialize`
uses it except if ~python_sigint:true is passed.
*)
let keep_sigint f =
let previous_signal_behavior = Sys.signal Sys.sigint Sys.Signal_ignore in
Sys.set_signal Sys.sigint previous_signal_behavior;
Stdcompat.Fun.protect f
~finally:(fun () -> Sys.set_signal Sys.sigint previous_signal_behavior)
let initialize ?library_name ?interpreter ?version
?minor ?(verbose = false) ?debug_build ?(python_sigint = false) () =
if !initialized then
failwith "Py.initialize: already initialized";
let do_initialize () =
match library_name with
| Some library_name ->
load_library (Some library_name);
| None ->
try
let python_full_path = find_interpreter interpreter version minor in
let interpreter_pythonpaths =
match python_full_path with
None -> []
| Some python_full_path' ->
pythonpaths_from_interpreter python_full_path' in
let new_pythonpaths =
List.rev_append !pythonpaths interpreter_pythonpaths in
if new_pythonpaths <> [] then
begin
let former_pythonpath = Sys.getenv_opt "PYTHONPATH" in
has_set_pythonpath := Some former_pythonpath;
let all_paths =
match former_pythonpath with
None -> new_pythonpaths
| Some former_pythonpath' ->
former_pythonpath' :: new_pythonpaths in
let pythonpath = String.concat path_separator all_paths in
if verbose then
begin
Printf.eprintf "Temporary set PYTHONPATH=\"%s\".\n" pythonpath;
flush stderr;
end;
Unix.putenv "PYTHONPATH" pythonpath
end;
let (version_major, version_minor) =
match python_full_path with
Some python_full_path' ->
let version_string =
python_version_from_interpreter python_full_path' in
let (version_major, version_minor) =
extract_version_major_minor version_string in
begin
match version with
None -> ()
| Some version_major' ->
if version_major <> version_major' then
failwith
(version_mismatch
python_full_path' (string_of_int version_major)
(string_of_int version_major'));
match minor with
None -> ()
| Some version_minor' ->
if version_minor <> version_minor' then
let expected =
build_version_string version_major version_minor in
let got =
build_version_string version_major' version_minor' in
failwith
(version_mismatch python_full_path' expected got);
end;
(Some version_major, Some version_minor)
| _ -> version, minor in
initialize_library ~verbose ~version_major ~version_minor ~debug_build
python_full_path;
with e ->
uninit_pythonhome ();
uninit_pythonpath ();
raise e in
if python_sigint then
do_initialize ()
else
keep_sigint do_initialize;
let version = get_version () in
let (version_major, version_minor) =
extract_version_major_minor version in
version_value := version;
version_major_value := version_major;
version_minor_value := version_minor;
initialized := true
let on_finalize_list = ref []
let on_finalize f = on_finalize_list := f :: !on_finalize_list
let finalize () =
assert_initialized ();
List.iter (fun f -> f ()) !on_finalize_list;
Gc.full_major ();
finalize_library ();
uninit_pythonhome ();
uninit_pythonpath ();
initialized := false
let version () =
assert_initialized ();
!version_value
let version_major () =
assert_initialized ();
!version_major_value
let version_minor () =
assert_initialized ();
!version_minor_value
let version_pair () =
assert_initialized ();
(!version_major_value, !version_minor_value)
let null =
pynull ()
let is_null v =
v == null
let none =
pynone ()
let is_none v =
v == none
exception E of pyobject * pyobject
let create_ref_to_python_object () =
let result = ref None in
on_finalize (fun () -> result := None);
result
let fetched_exception = create_ref_to_python_object ()
let ocaml_exception_class = create_ref_to_python_object ()
let ocaml_exception_capsule = create_ref_to_python_object ()
let python_exception () =
let ptype, pvalue, ptraceback = pyerr_fetch_internal () in
if
match !ocaml_exception_class with
| None -> false
| Some ocaml_exception_class ->
Lazy.is_val ocaml_exception_class &&
Lazy.force ocaml_exception_class = ptype
then
begin
let args = Pywrappers.pyobject_getattrstring pvalue "args" in
assert (args <> null);
let capsule = Pywrappers.pysequence_getitem args 0 in
assert (capsule <> null);
let exc, bt = snd (Option.get !ocaml_exception_capsule) capsule in
Printexc.raise_with_backtrace exc bt
end
else
begin
fetched_exception := Some (ptype, pvalue, ptraceback);
raise (E (ptype, pvalue))
end
let check_not_null result =
if result = null then
python_exception ();
result
let check_some s =
match s with
None -> python_exception ()
| Some s -> s
let check_error () =
if Pywrappers.pyerr_occurred () <> null then
python_exception ()
let check_int result =
if result = -1 then
python_exception ()
else
result
let check_int64 result =
if result = -1L then
python_exception ()
else
result
let assert_int_success result =
if result = -1 then
python_exception ()
let bool_of_int i = check_int i <> 0
let get_program_name () =
if !initialized then
if !version_major_value <= 2 then
Pywrappers.Python2.py_getprogramname ()
else
Pywrappers.Python3.py_getprogramname ()
else
!program_name
let get_python_home () =
if !initialized then
if !version_major_value <= 2 then
Pywrappers.Python2.py_getpythonhome ()
else
Pywrappers.Python3.py_getpythonhome ()
else
match !python_home with
None -> ""
| Some s -> s
let get_program_full_path () =
if version_major () <= 2 then
Pywrappers.Python2.py_getprogramfullpath ()
else
Pywrappers.Python3.py_getprogramfullpath ()
let get_prefix () =
if version_major () <= 2 then
Pywrappers.Python2.py_getprogramfullpath ()
else
Pywrappers.Python3.py_getprogramfullpath ()
let get_exec_prefix () =
if version_major () <= 2 then
Pywrappers.Python2.py_getexecprefix ()
else
Pywrappers.Python3.py_getexecprefix ()
let get_path () =
if version_major () <= 2 then
Pywrappers.Python2.py_getpath ()
else
Pywrappers.Python3.py_getpath ()
let get_platform = Pywrappers.py_getplatform
let get_copyright = Pywrappers.py_getcopyright
let get_compiler = Pywrappers.py_getcompiler
let get_build_info = Pywrappers.py_getbuildinfo
let option result =
if result = null then
begin
check_error ();
None
end
else
Some result
let check_found result =
if result = null then
begin
check_error ();
raise Not_found
end
else
result
let option_of_error result =
if result = null then
begin
let _ = pyerr_fetch_internal () in
None
end
else
Some result
let assert_not_null function_name obj =
if is_null obj then
invalid_arg (function_name ^ ": unallowed null argument")
module Eval = struct
let call_object_with_keywords func arg keyword =
assert_not_null "call_object_with_keywords(!, _, _)" func;
assert_not_null "call_object_with_keywords(_, !, _)" arg;
check_not_null (Pywrappers.pyeval_callobjectwithkeywords func arg keyword)
let call_object func arg =
call_object_with_keywords func arg null
let get_builtins () = check_not_null (Pywrappers.pyeval_getbuiltins ())
let get_globals () = check_not_null (Pywrappers.pyeval_getglobals ())
let get_locals () = check_not_null (Pywrappers.pyeval_getlocals ())
end
let object_repr obj = check_not_null (Pywrappers.pyobject_repr obj)
module String_ = struct
let as_UTF8_string s =
assert_not_null "as_UTF8_string" s;
let f =
match ucs () with
UCS2 -> Pywrappers.UCS2.pyunicodeucs2_asutf8string
| UCS4 -> Pywrappers.UCS4.pyunicodeucs4_asutf8string
| UCSNone ->
if !version_major_value >= 3 then
Pywrappers.Python3.pyunicode_asutf8string
else
failwith "String.as_UTF8_string: unavailable" in
check_not_null (f s)