forked from thonny/thonny
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunning.py
More file actions
1990 lines (1627 loc) · 68.5 KB
/
Copy pathrunning.py
File metadata and controls
1990 lines (1627 loc) · 68.5 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
# -*- coding: utf-8 -*-
"""Code for maintaining the background process and for running
user programs
Commands get executed via shell, this way the command line in the
shell becomes kind of title for the execution.
"""
import collections
import os.path
import queue
import re
import shlex
import shutil
import subprocess
import sys
import threading
import time
import tkinter as tk
import traceback
import warnings
from abc import ABC, abstractmethod
from logging import getLogger
from threading import Thread
from time import sleep
from tkinter import messagebox, ttk
from typing import Any, Callable, Dict, List, Optional, Tuple, Union # @UnusedImport; @UnusedImport
import pystart
from pystart import (
common,
get_runner,
get_shell,
get_pystart_user_dir,
get_vendored_libs_dir,
get_version,
get_workbench,
report_time,
)
from pystart.common import (
ALL_EXPLAINED_STATUS_CODE,
PROCESS_ACK,
BackendEvent,
CommandToBackend,
DebuggerCommand,
DebuggerResponse,
DistInfo,
EOFCommand,
InlineCommand,
InlineResponse,
InputSubmission,
MessageFromBackend,
ToplevelCommand,
ToplevelResponse,
UserError,
is_same_path,
parse_message,
path_startswith,
read_one_incoming_message_str,
serialize_message,
try_get_base_executable,
universal_relpath,
update_system_path,
)
from pystart.editors import (
get_current_breakpoints,
get_saved_current_script_path,
get_target_dir_from_uri,
)
from pystart.languages import tr
from pystart.misc_utils import (
UNTITLED_URI_SCHEME,
construct_cmd_line,
inside_flatpak,
is_local_uri,
is_remote_uri,
running_on_mac_os,
running_on_windows,
show_command_not_available_in_flatpak_message,
uri_to_target_path,
)
from pystart.ui_utils import select_sequence, show_dialog
from pystart.workdlg import WorkDialog
logger = getLogger(__name__)
WINDOWS_EXE = "python.exe"
OUTPUT_MERGE_THRESHOLD = 1000
RUN_COMMAND_LABEL = "" # init later when gettext is ready
RUN_COMMAND_CAPTION = ""
EDITOR_CONTENT_TOKEN = "$EDITOR_CONTENT"
INTERRUPT_SEQUENCE = "<Control-c>"
CSI_TERMINATOR = re.compile("[@-~]")
OSC_TERMINATOR = re.compile(r"\a|\x1B\\")
TERMINATION_TIMEOUT = 2
TERMINATION_POLL_INTERVAL = 0.02
# other components may turn it on in order to avoid grouping output lines into one event
io_animation_required = False
_console_allocated = False
BASE_MODULES = [
"_abc",
"_codecs",
"_collections_abc",
"_distutils_hack",
"_frozen_importlib",
"_frozen_importlib_external",
"_imp",
"_io",
"_signal",
"_sitebuiltins",
"_stat",
"_thread",
"_warnings",
"_weakref",
"_winapi",
"abc",
"builtins",
"codecs",
"encodings",
"genericpath",
"io",
"marshal",
"nt",
"ntpath",
"os",
"site",
"stat",
"sys",
"time",
"winreg",
"zipimport",
]
class Runner:
def __init__(self) -> None:
get_workbench().set_default("run.allow_running_unnamed_programs", True)
get_workbench().set_default("run.auto_cd", True)
get_workbench().set_default("run.warn_module_shadowing", True)
self._init_commands()
self._state = "starting"
self._proxy: Optional[BackendProxy] = None
self._publishing_events = False
self._polling_after_id = None
self._postponed_commands = [] # type: List[CommandToBackend]
self._thread_commands = queue.Queue()
self._thread_command_results = {}
self._running_thread_command_ids = set()
self._last_accepted_backend_command = None
def start(self) -> None:
global _console_allocated
try:
self._check_alloc_console()
_console_allocated = True
except Exception:
logger.exception("Problem allocating console")
_console_allocated = False
try:
self.restart_backend(False, True)
except Exception as e:
logger.exception("Could not start backend when starting Runner")
get_shell().print_error(f"\nStarting the back-end failed with following error: {e}\n")
def _init_commands(self) -> None:
global RUN_COMMAND_CAPTION, RUN_COMMAND_LABEL
RUN_COMMAND_LABEL = tr("Run current script")
RUN_COMMAND_CAPTION = tr("Run")
get_workbench().set_default("run.run_in_terminal_python_repl", False)
get_workbench().set_default("run.run_in_terminal_keep_open", True)
try:
import pystart.plugins.debugger # @UnusedImport
debugger_available = True
except ImportError:
debugger_available = False
get_workbench().add_command(
"run_current_script",
"run",
RUN_COMMAND_LABEL,
caption=RUN_COMMAND_CAPTION,
handler=self.cmd_run_current_script,
default_sequence="<F5>",
extra_sequences=[select_sequence("<Control-r>", "<Command-r>")],
tester=self.cmd_run_current_script_enabled,
group=10,
image="run-current-script",
include_in_toolbar=not (get_workbench().in_simple_mode() and debugger_available),
show_extra_sequences=True,
)
get_workbench().add_command(
"run_current_script_in_terminal",
"run",
tr("Run current script in terminal"),
caption="RunT",
handler=self._cmd_run_current_script_in_terminal,
default_sequence="<Control-t>",
extra_sequences=["<<CtrlTInText>>"],
tester=self._cmd_run_current_script_in_terminal_enabled,
group=35,
image="terminal",
)
get_workbench().add_command(
"restart",
"run",
tr("Stop/Restart backend"),
caption=tr("Stop"),
handler=self.cmd_stop_restart,
default_sequence="<Control-F2>",
group=100,
image="stop",
include_in_toolbar=True,
)
get_workbench().add_command(
"interrupt",
"run",
tr("Interrupt execution"),
handler=self._cmd_interrupt,
tester=self._cmd_interrupt_enabled,
default_sequence=INTERRUPT_SEQUENCE,
skip_sequence_binding=True, # Sequence will be bound differently
group=100,
bell_when_denied=False,
)
get_workbench().bind(INTERRUPT_SEQUENCE, self._cmd_interrupt_with_shortcut, True)
get_workbench().add_command(
"ctrld",
"run",
tr("Send EOF / Soft reboot"),
self.ctrld,
self.ctrld_enabled,
group=100,
default_sequence="<Control-d>",
extra_sequences=["<<CtrlDInText>>"],
)
get_workbench().add_command(
"disconnect",
"run",
tr("Disconnect"),
self.disconnect,
self.disconnect_enabled,
group=100,
)
def get_state(self) -> str:
"""State is one of "running", "waiting_debugger_command", "waiting_toplevel_command" """
return self._state
def _set_state(self, state: str) -> None:
if self._state != state:
logger.debug("Runner state changed: %s ==> %s" % (self._state, state))
self._state = state
def is_running(self):
return self._state == "running"
def is_waiting(self):
return self._state.startswith("waiting")
def is_waiting_toplevel_command(self):
return self._state == "waiting_toplevel_command"
def is_waiting_debugger_command(self):
return self._state == "waiting_debugger_command"
def get_sys_path(self) -> List[str]:
return self._proxy.get_sys_path()
def send_command(self, cmd: CommandToBackend) -> None:
logger.info("Runner.send_command %r", cmd)
self._send_initial_or_queued_command(cmd)
def _send_initial_or_queued_command(self, cmd: CommandToBackend) -> None:
if self._proxy is None:
return
if self._publishing_events:
# allow all event handlers to complete before sending the commands
# issued by first event handlers
self._postpone_command(cmd, "there are events to be published")
return
# First sanity check
if (
isinstance(cmd, ToplevelCommand)
and not self.is_waiting_toplevel_command()
and cmd.name not in ["Reset", "Run", "Debug"]
or isinstance(cmd, DebuggerCommand)
and not self.is_waiting_debugger_command()
):
get_workbench().bell()
logger.warning("RUNNER: Command %s was attempted at state %s" % (cmd, self.get_state()))
return
# Attach extra info
if "debug" in cmd.name.lower():
cmd["breakpoints"] = get_current_breakpoints()
if "id" not in cmd:
cmd["id"] = generate_command_id()
cmd["local_cwd"] = get_workbench().get_local_cwd()
if self._proxy.running_inline_command and isinstance(cmd, InlineCommand):
reason = "running another inline command"
cur_cmd_name = getattr(self._last_accepted_backend_command, "name", None)
if cur_cmd_name:
reason += f" ({cur_cmd_name})"
self._postpone_command(cmd, reason)
return
# Offer the command
logger.debug("Runner: sending command %r to proxy: %s", cmd.name, cmd)
try:
response = self._proxy.send_command(cmd)
except Exception as e:
logger.exception("proxy raised exception for command")
get_shell().print_error(f"\nCommand {cmd.name} failed with following error: {e}\n")
return None
logger.debug("send_command response from proxy: %r", response)
if response == "discard":
logger.info("back-end discarded the command")
return None
elif response == "postpone":
self._postpone_command(cmd, "back-end requested postpone")
return
else:
assert response is None
get_workbench().event_generate("CommandAccepted", command=cmd)
self._last_accepted_backend_command = cmd
if isinstance(cmd, InlineCommand):
self._proxy.running_inline_command = True
if isinstance(cmd, (ToplevelCommand, DebuggerCommand)):
self._set_state("running")
if cmd.name[0].isupper():
# This may be only logical restart, which does not look like restart to the runner
get_workbench().event_generate("BackendRestart", full=False)
def send_command_and_wait(self, cmd: InlineCommand, dialog_title: str) -> MessageFromBackend:
dlg = InlineCommandDialog(get_workbench(), cmd, title=dialog_title + " ...")
show_dialog(dlg)
return dlg.response
def send_command_and_wait_in_thread(
self, cmd: InlineCommand, timeout: int
) -> MessageFromBackend:
logger.info("Runner.send_command_and_wait_in_thread %r", cmd)
# should not send directly, as we're in thread
cmd_id = cmd.get("id")
if cmd_id is None:
cmd_id = generate_command_id()
cmd["id"] = cmd_id
start_time = time.time()
proxy_at_start = self._proxy
self._thread_commands.put(cmd)
while time.time() - start_time < timeout:
if self._proxy is not proxy_at_start:
raise RuntimeError("Backend restarted")
elif cmd_id in self._thread_command_results:
result = self._thread_command_results[cmd_id]
del self._thread_command_results[cmd_id]
return result
else:
time.sleep(0.1)
else:
raise TimeoutError(f"Could not receive response to {cmd} in {timeout} seconds")
def _postpone_command(self, cmd: CommandToBackend, reason: str) -> None:
logger.info("Postponing command. Reason: %s", reason)
# in case of InlineCommands, discard older same type command
if isinstance(cmd, InlineCommand):
for older_cmd in self._postponed_commands:
if older_cmd.name == cmd.name:
logger.info("Discarding older command of same type")
self._postponed_commands.remove(older_cmd)
if len(self._postponed_commands) > 10:
logger.warning("Can't pile up too many commands. This command will be just ignored")
else:
self._postponed_commands.append(cmd)
def _send_postponed_commands(self) -> None:
todo = self._postponed_commands
self._postponed_commands = []
for cmd in todo:
logger.info("Sending postponed command: %s", cmd)
self._send_initial_or_queued_command(cmd)
def _send_thread_commands(self) -> None:
while not self._thread_commands.empty():
cmd = self._thread_commands.get()
self._running_thread_command_ids.add(cmd["id"])
logger.info("Sending thread command: %s", cmd)
self._send_initial_or_queued_command(cmd)
def send_program_input(self, data: str) -> None:
assert self.is_running()
self._proxy.send_program_input(data)
def execute_via_shell(
self,
cmd_line: Union[str, List[str]],
working_directory: Optional[str] = None,
) -> None:
if working_directory and self._proxy.get_cwd() != working_directory:
# create compound command
# start with %cd
cd_cmd_line = construct_cd_command(working_directory) + "\n"
else:
# create simple command
cd_cmd_line = ""
if not isinstance(cmd_line, str):
cmd_line = construct_cmd_line(cmd_line)
# submit to shell (shell will execute it)
get_shell().submit_magic_command(cd_cmd_line + cmd_line)
def execute_script(
self,
script_path: str,
args: List[str],
working_directory: Optional[str],
command_name: str = "Run",
) -> None:
rel_filename = universal_relpath(script_path, working_directory)
cmd_parts = ["%" + command_name, rel_filename] + args
cmd_line = construct_cmd_line(cmd_parts, [EDITOR_CONTENT_TOKEN])
self.execute_via_shell(cmd_line, working_directory)
def execute_editor_content(self, command_name, args):
if command_name.lower() in ["debug", "fastdebug"]:
messagebox.showinfo(
tr("Information"),
tr("For debugging the program must be saved first."),
master=get_workbench(),
)
return
get_shell().submit_magic_command(
construct_cmd_line(
["%" + command_name, "-c", EDITOR_CONTENT_TOKEN] + args, [EDITOR_CONTENT_TOKEN]
)
)
def execute_current(self, command_name: str) -> None:
"""
This method's job is to create a command for running/debugging
current file/script and submit it to shell
"""
if not self._proxy:
return
assert (
command_name[0].isupper()
or command_name == "run"
and not self._proxy.should_restart_interpreter_before_run()
)
if not self.is_waiting_toplevel_command():
logger.info("Trying to execute current but runner is %r", self.get_state())
self._proxy.interrupt()
try:
self._wait_for_prompt(1)
except TimeoutError:
# turtle.mainloop, for example, is not easy to interrupt.
get_shell().print_error("Could not interrupt current process. ")
wait_instructions = "Please wait, try again or select Stop/Restart!"
if self._proxy.stop_restart_kills_user_program():
get_shell().print_error("Forcing the program to stop.\n")
self.cmd_stop_restart()
try:
self._wait_for_prompt(1)
except TimeoutError:
get_shell().print_error(
"Could not force-stop the program. " + wait_instructions + "\n"
)
else:
# For some back-ends (e.g. BareMetalMicroPython) killing is not an option.
# Besides, they may be configured to avoid refreshing the environment
# before run (for performance reasons).
get_shell().print_error(wait_instructions + "\n")
return
editor = get_workbench().get_editor_notebook().get_current_editor()
if not editor:
return
UNTITLED = f"{UNTITLED_URI_SCHEME}:0"
if not editor.is_untitled() or not get_workbench().get_option(
"run.allow_running_unnamed_programs"
):
if not editor.is_untitled() and not editor.is_modified():
# Don't attempt to save as the file may be read-only
logger.debug("Not saving read only file %s", editor.get_uri())
uri = editor.get_uri()
else:
uri = editor.save_file()
if not uri:
# user has cancelled file saving
return
else:
uri = UNTITLED
if not self._proxy:
# Saving the file may have killed the proxy
return
if (
is_remote_uri(uri)
and not self._proxy.can_run_remote_files()
or is_local_uri(uri)
and not self._proxy.can_run_local_files()
or uri == UNTITLED
):
self.execute_editor_content(command_name, self._get_active_arguments())
else:
if get_workbench().get_option("run.auto_cd") and command_name[0].isupper():
working_directory = get_target_dir_from_uri(uri)
else:
working_directory = self._proxy.get_cwd()
target_path = uri_to_target_path(uri)
self.execute_script(
target_path, self._get_active_arguments(), working_directory, command_name
)
def _wait_for_prompt(self, timeout) -> None:
start_time = time.time()
while time.time() - start_time <= timeout:
if self.is_waiting_toplevel_command():
return
get_workbench().update()
sleep(0.01)
raise TimeoutError("Backend did not respond in time")
def _get_active_arguments(self):
if get_workbench().get_option("view.show_program_arguments"):
args_str = get_workbench().get_option("run.program_arguments")
get_workbench().log_program_arguments_string(args_str)
return shlex.split(args_str)
else:
return []
def cmd_run_current_script_enabled(self) -> bool:
return (
self._proxy and get_workbench().get_editor_notebook().get_current_editor() is not None
)
def _cmd_run_current_script_in_terminal_enabled(self) -> bool:
return (
self._proxy
and self._proxy.can_run_in_terminal()
and self.cmd_run_current_script_enabled()
)
def cmd_run_current_script(self) -> None:
if get_workbench().in_simple_mode():
get_workbench().hide_view("VariablesView")
report_time("Before Run")
if self._proxy and self._proxy.should_restart_interpreter_before_run():
self.execute_current("Run")
else:
self.execute_current("run")
report_time("After Run")
def _cmd_run_current_script_in_terminal(self) -> None:
if inside_flatpak():
show_command_not_available_in_flatpak_message()
return
path = get_saved_current_script_path()
if not path:
return
self._proxy.run_script_in_terminal(
path,
self._get_active_arguments(),
get_workbench().get_option("run.run_in_terminal_python_repl"),
get_workbench().get_option("run.run_in_terminal_keep_open"),
)
def _cmd_interrupt(self) -> None:
if self._proxy is not None:
if _console_allocated:
self._proxy.interrupt()
else:
messagebox.showerror(
"No console",
"Can't interrupt as console was not allocated.\n\nUse Stop/Restart instead.",
master=self,
)
else:
logger.warning("User tried interrupting without proxy")
def _cmd_interrupt_with_shortcut(self, event=None):
if not self._cmd_interrupt_enabled():
return None
if not running_on_mac_os(): # on Mac Ctrl+C is not used for Copy.
# Disable Ctrl+C interrupt in editor and shell, when some text is selected
# (assuming user intended to copy instead of interrupting)
widget = get_workbench().focus_get()
if isinstance(widget, tk.Text):
if len(widget.tag_ranges("sel")) > 0:
# this test is reliable, unlike selection_get below
return None
elif isinstance(widget, (tk.Listbox, ttk.Entry, tk.Entry, tk.Spinbox)):
try:
# NB! On Linux, selection_get() gives X selection
# i.e. it may be from another application when PyStart has nothing selected
selection = widget.selection_get()
if isinstance(selection, str) and len(selection) > 0:
# Assuming user meant to copy, not interrupt
# (IDLE seems to follow same logic)
# NB! This is not perfect, as in Linux the selection can be in another app
# ie. there may be no selection in PyStart actually.
# In other words, Ctrl+C interrupt may be dropped without reason
# when given inside the widgets listed above.
return None
except Exception:
# widget either doesn't have selection_get or it
# gave error (can happen without selection on Ubuntu)
pass
self._cmd_interrupt()
return "break"
def _cmd_interrupt_enabled(self) -> bool:
return self._proxy and self._proxy.is_connected()
def cmd_stop_restart(self) -> None:
if get_workbench().in_simple_mode():
get_workbench().hide_view("VariablesView")
self.restart_backend(clean=True)
def disconnect(self):
proxy = self.get_backend_proxy()
assert hasattr(proxy, "disconnect")
proxy.disconnect()
def disconnect_enabled(self):
proxy = self.get_backend_proxy()
return proxy is not None and proxy.needs_disconnect_button()
def ctrld(self):
proxy = self.get_backend_proxy()
if not proxy:
return
if get_shell().has_pending_input():
messagebox.showerror(
"Can't perform this action",
"Ctrl+D only has effect on an empty line / prompt.\n"
+ "Submit current input (press ENTER) and try again",
master=get_workbench(),
)
return
proxy.send_command(EOFCommand())
self._set_state("running")
def ctrld_enabled(self):
proxy = self.get_backend_proxy()
return proxy and proxy.is_connected()
def _poll_backend_messages(self) -> None:
"""I chose polling instead of event_generate in listener thread,
because event_generate across threads is not reliable
http://www.thecodingforums.com/threads/more-on-tk-event_generate-and-threads.359615/
"""
self._polling_after_id = None
if self._pull_backend_messages() is False:
return
if self._proxy.has_next_message():
# Some events didn't fit into this batch. Start the next batch as soon as possible
self._polling_after_id = get_workbench().after_idle(self._poll_backend_messages)
else:
# take it easy
self._polling_after_id = get_workbench().after(
20, lambda: get_workbench().after_idle(self._poll_backend_messages)
)
def _pull_backend_messages(self):
# Don't process too many messages in single batch, allow screen updates
# and user actions between batches.
# Mostly relevant when backend prints a lot quickly.
# TODO: Should I leave new messages (caused by processing this batch) for next batch?
msg_count = 0
max_msg_count = 10
while self._proxy is not None and msg_count < max_msg_count:
try:
msg = self._proxy.fetch_next_message()
if not msg:
break
logger.debug("RUNNER GOT: %s in state: %s", msg.event_type, self.get_state())
msg_count += 1
except BackendTerminatedError as exc:
logger.info("Backend terminated with code: %r", exc.returncode)
self._handle_backend_termination(exc.returncode)
return False
# change state
if isinstance(msg, ToplevelResponse):
self._set_state("waiting_toplevel_command")
elif isinstance(msg, DebuggerResponse):
self._set_state("waiting_debugger_command")
elif isinstance(msg, InlineResponse):
# next inline command won't be sent before response from the last has arrived
self._proxy.running_inline_command = False
else:
"other messages don't affect the state"
command_id = msg.get("command_id")
if command_id in self._running_thread_command_ids:
self._running_thread_command_ids.remove(command_id)
self._thread_command_results[command_id] = msg
else:
# Publish the event
# NB! This may cause another command to be sent before we get to postponed commands
try:
self._publishing_events = True
class_event_type = type(msg).__name__
get_workbench().event_generate(
class_event_type, event=msg
) # more general event
if msg.event_type != class_event_type:
# more specific event
get_workbench().event_generate(msg.event_type, event=msg)
finally:
self._publishing_events = False
# TODO: is it necessary???
# https://stackoverflow.com/a/13520271/261181
# get_workbench().update()
self._send_thread_commands()
self._send_postponed_commands()
def _handle_backend_termination(self, returncode: Optional[int]) -> None:
if returncode is None or returncode == ALL_EXPLAINED_STATUS_CODE:
err = ""
else:
err = f"Process ended with exit code {returncode}."
try:
faults_file = os.path.join(get_pystart_user_dir(), "backend_faults.log")
if os.path.exists(faults_file):
with open(faults_file, encoding="ASCII", errors="replace") as fp:
err += fp.read()
except Exception:
logger.exception("Failed retrieving backend faults")
get_workbench().event_generate("ProgramOutput", stream_name="stderr", data="\n" + err)
get_workbench().become_active_window(False)
self.destroy_backend()
if self._should_restart_after_command(self._last_accepted_backend_command):
self.restart_backend(clean=True, automatic=True)
def _should_restart_after_command(self, cmd: CommandToBackend):
if cmd is None or not hasattr(cmd, "name"):
return False
return cmd.name in ["Run", "run", "Debug", "debug", "execute_source"]
def restart_backend(self, clean: bool, first: bool = False, automatic: bool = False) -> None:
"""Recreate (or replace) backend proxy / backend process."""
logger.info(
"Restarting back-end, clean: %r, first: %r, automatic: %r", clean, first, automatic
)
was_running = self.is_running()
self.destroy_backend()
self._last_accepted_backend_command = None
backend_name = get_workbench().get_option("run.backend_name")
if backend_name not in get_workbench().get_backends():
raise UserError(
f"Unknown interpreter kind '{backend_name}'. Please select another interpreter from options"
)
backend_class = get_workbench().get_backends()[backend_name].proxy_class
self._set_state("running")
self._proxy = None
logger.info("Starting backend %r", backend_class)
self._proxy = backend_class(clean)
if not first:
get_shell().restart(automatic=automatic, was_running=was_running)
get_shell().update_idletasks()
get_workbench().event_generate("BackendRestart", full=True)
get_workbench().after_idle(self._poll_backend_messages)
def destroy_backend(self, for_restart: bool = False) -> None:
logger.info("Destroying backend")
if self._polling_after_id is not None:
get_workbench().after_cancel(self._polling_after_id)
self._polling_after_id = None
self._postponed_commands = []
if self._proxy:
self._proxy.destroy(for_restart=for_restart)
self._proxy = None
get_workbench().event_generate("BackendTerminated")
def get_backend_proxy(self) -> "BackendProxy":
return self._proxy
def _check_alloc_console(self) -> None:
if sys.executable.endswith("pythonw.exe"):
# These don't have console allocated.
# Console is required for sending interrupts.
# AllocConsole would be easier but flashes console window
import ctypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
exe = sys.executable.replace("pythonw.exe", "python.exe")
cmd = [exe, "-c", "print('Hi!'); input()"]
child = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
)
child.stdout.readline()
result = kernel32.AttachConsole(child.pid)
if not result:
err = ctypes.get_last_error()
logger.info("Could not allocate console. Error code: " + str(err))
child.stdin.write(b"\n")
try:
child.stdin.flush()
except Exception:
# May happen eg. when installation path has "&" in it
# See https://bitbucket.org/plas/pystart/issues/508/cant-allocate-windows-console-when
# Without flush the console window becomes visible, but PyStart can be still used
logger.exception("Problem with finalizing console allocation")
def ready_for_remote_file_operations(self, show_message=False):
if not self._proxy or not self.supports_remote_files():
return False
ready = self._proxy.ready_for_remote_file_operations()
if not ready and show_message:
if not self._proxy.is_connected():
msg = "Device is not connected"
else:
msg = (
"Device is busy -- can't perform this action now."
+ "\nPlease wait or cancel current work and try again!"
)
messagebox.showerror(tr("Can't complete"), msg, master=get_workbench())
return ready
def supports_remote_files(self):
if self._proxy is None:
return False
else:
return self._proxy.supports_remote_files()
def supports_remote_directories(self):
if self._proxy is None:
return False
else:
return self._proxy.supports_remote_directories()
def get_node_label(self):
if self._proxy is None:
return "Back-end"
else:
return self._proxy.get_node_label()
def using_venv(self) -> bool:
from pystart.plugins.cpython_frontend import LocalCPythonProxy
from pystart.plugins.cpython_ssh.cps_front import SshCPythonProxy
return (
isinstance(self._proxy, (LocalCPythonProxy, SshCPythonProxy)) and self._proxy._in_venv
)
def is_connected(self):
if self._proxy is None:
return False
else:
return self._proxy.is_connected()
class BackendProxy(ABC):
"""Communicates with backend process.
All communication methods must be non-blocking,
ie. suitable for calling from GUI thread."""
# backend_name will be overwritten on Workbench.add_backend
# Subclasses don't need to worry about it.
backend_name = None
backend_description = None
def __init__(self, clean: bool) -> None:
"""Initializes (or starts the initialization of) the backend process.
Backend is considered ready when the runner gets a ToplevelResponse
with attribute "welcome_text" from fetch_next_message.
"""
self.running_inline_command = False
@abstractmethod
def send_command(self, cmd: CommandToBackend) -> Optional[str]:
"""Send the command to backend. Return None, 'discard' or 'postpone'"""
@abstractmethod
def send_program_input(self, data: str) -> None:
"""Send input data to backend"""
@abstractmethod
def has_next_message(self) -> bool: ...
@abstractmethod
def fetch_next_message(self):
"""Read next message from the queue or None if queue is empty"""
@abstractmethod
def get_sys_path(self):
"backend's sys.path"
...
@abstractmethod
def get_board_id(self): ...
def get_backend_name(self):
return type(self).backend_name
@abstractmethod
def interrupt(self):
"""Tries to interrupt current command without resetting the backend"""
...
@abstractmethod
def destroy(self, for_restart: bool = False):
"""Called when PyStart no longer needs this instance
(PyStart gets closed or new backend gets selected)
"""
...
@abstractmethod
def is_connected(self) -> bool:
"""Returns True if the backend is operational.
Returns False if the connection is lost (or not created yet)
or the remote process has died (or not created yet).
"""
...
def disconnect(self):
"""
Means different things for different backends.