Debian Codegraph @

DisplayCAL/wexpect.py

raw
1 """Pexpect: spawn child applications and control them automatically in Python.
2
3 Pexpect can be used for automating interactive applications
4 such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
5 scripts for duplicating software package installations on different servers. It
6 can be used for automated software testing. Pexpect is in the spirit of Don
7 Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
8 require TCL and Expect or require C extensions to be compiled. Pexpect does not
9 use C, Expect, or TCL extensions. It should work on any platform that supports
10 the standard Python pty module. The Pexpect interface focuses on ease of use so
11 that simple tasks are easy.
12
13 There are two main interfaces to Pexpect -- the function, run() and the class,
14 spawn. You can call the run() function to execute a command and return the
15 output. This is a handy replacement for os.system().
16
17 For example::
18
19 pexpect.run('ls -la')
20
21 The more powerful interface is the spawn class. You can use this to spawn an
22 external child command and then interact with the child by sending lines and
23 expecting responses.
24
25 For example::
26
27 child = pexpect.spawn('scp foo [email protected]:.')
28 child.expect ('Password:')
29 child.sendline (mypassword)
30
31 This works even for commands that ask for passwords or other input outside of
32 the normal stdio streams.
33
34 Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
35 Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
36 vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
37 Geoffrey Marshall, Francisco Lourenco, Glen Mabey, Karthik Gurusamy, Fernando
38 Perez, Corey Minyard, Jon Cohen, Guillaume Chazarain, Andrew Ryan, Nick
39 Craig-Wood, Andrew Stone, Jorgen Grahn (Let me know if I forgot anyone.)
40
41 Free, open source, and all that good stuff.
42
43 Permission is hereby granted, free of charge, to any person obtaining a copy of
44 this software and associated documentation files (the "Software"), to deal in
45 the Software without restriction, including without limitation the rights to
46 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
47 of the Software, and to permit persons to whom the Software is furnished to do
48 so, subject to the following conditions:
49
50 The above copyright notice and this permission notice shall be included in all
51 copies or substantial portions of the Software.
52
53 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
56 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
58 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
59 SOFTWARE.
60
61 Pexpect Copyright (c) 2008 Noah Spurrier
62 http://pexpect.sourceforge.net/
63
64 $Id: pexpect.py 507 2007-12-27 02:40:52Z noah $
65 """
66
67 from __future__ import annotations
68
69 import contextlib
70 import errno
71 import os
72 import re
73 import select
74 import signal
75 import string
76 import struct
77 import sys
78 import time
79 import traceback
80 from typing import TYPE_CHECKING
81
82 if TYPE_CHECKING:
83 if sys.version_info >= (3, 11):
84 from typing import Self
85 else:
86 from typing_extensions import Self
87
88
89 if sys.platform != "win32":
90 import fcntl
91 import pty
92 import resource
93 import termios
94 import tty
95 else:
96 from ctypes import windll
97 from io import StringIO
98
99 import pywintypes
100 import win32api
101 import win32file
102 from win32com.shell.shell import SHGetSpecialFolderPath
103 from win32com.shell.shellcon import CSIDL_APPDATA
104 from win32con import (
105 CREATE_NEW_CONSOLE,
106 CREATE_NEW_PROCESS_GROUP,
107 CTRL_BREAK_EVENT,
108 FILE_SHARE_READ,
109 FILE_SHARE_WRITE,
110 GENERIC_READ,
111 GENERIC_WRITE,
112 OPEN_EXISTING,
113 PM_REMOVE,
114 PROCESS_QUERY_INFORMATION,
115 PROCESS_TERMINATE,
116 STARTF_USESHOWWINDOW,
117 STILL_ACTIVE,
118 SW_HIDE,
119 SW_SHOW,
120 THREAD_SUSPEND_RESUME,
121 WM_USER,
122 )
123 from win32console import (
124 KEY_EVENT,
125 STD_INPUT_HANDLE,
126 AllocConsole,
127 AttachConsole,
128 FreeConsole,
129 GetConsoleProcessList,
130 GetConsoleWindow,
131 GetStdHandle,
132 PyConsoleScreenBufferType,
133 PyCOORDType,
134 PyINPUT_RECORDType,
135 PySMALL_RECTType,
136 SetConsoleOutputCP,
137 SetConsoleTitle,
138 )
139 from win32gui import (
140 PeekMessage,
141 ShowWindow,
142 )
143 from win32process import (
144 CreateProcess,
145 GetCurrentProcessId,
146 GetExitCodeProcess,
147 GetStartupInfo,
148 GetWindowThreadProcessId,
149 ResumeThread,
150 SuspendThread,
151 TerminateProcess,
152 )
153
154
155 __version__ = "2.3"
156 __revision__ = "$Revision: 399 $"
157 __all__ = [
158 "EOF",
159 "TIMEOUT",
160 "ExceptionPexpect",
161 "__revision__",
162 "__version__",
163 "run",
164 "spawn",
165 "split_command_line",
166 "which",
167 ]
168
169
170 from DisplayCAL.meta import NAME as APPNAME
171
172
173 # Exception classes used by this module.
174 class ExceptionPexpect(Exception): # noqa: N818
175 """Base class for all exceptions raised by this module."""
176
177 def __init__(self, value):
178 self.value = value
179
180 def __str__(self) -> str:
181 """Return a string representation of the exception.
182
183 Returns:
184 str: A string representation of the exception.
185 """
186 return str(self.value)
187
188 def get_trace(self):
189 """Return an abbreviated stack trace with lines that only concern the caller.
190
191 In other words, the stack trace inside the Pexpect module is not
192 included.
193 """
194 tblist = traceback.extract_tb(sys.exc_info()[2])
195 # tblist = filter(self.__filter_not_pexpect, tblist)
196 tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
197 tblist = traceback.format_list(tblist)
198 return "".join(tblist)
199
200 def __filter_not_pexpect(self, trace_list_item):
201 """Return True if list item 0 the string 'pexpect.py' in it."""
202 return trace_list_item[0].find("pexpect.py") == -1
203
204
205 class EOF(ExceptionPexpect):
206 """Raised when EOF is read from a child. This usually means the child has exited."""
207
208
209 class TIMEOUT(ExceptionPexpect):
210 """Raised when a read time exceeds the timeout."""
211
212
213 # class TIMEOUT_PATTERN(TIMEOUT):
214 # """Raised when the pattern match time exceeds the timeout.
215 # This is different than a read TIMEOUT because the child process may
216 # give output, thus never give a TIMEOUT, but the output
217 # may never match a pattern.
218 # """
219 # class MAXBUFFER(ExceptionPexpect):
220 # """Raised when a scan buffer fills before matching an expected pattern."""
221
222
223 def run(
224 command,
225 timeout=-1,
226 withexitstatus=False,
227 events=None,
228 extra_args=None,
229 logfile=None,
230 cwd=None,
231 env=None,
232 ):
233 r"""Run the given command, wait for it to finish, return all output as a string.
234
235 STDERR is included in output. If the full path to the command is not given
236 then the path is searched.
237
238 Note that lines are terminated by CR/LF (\r\n) combination even on
239 UNIX-like systems because this is the standard for pseudo ttys. If you set
240 'withexitstatus' to true, then run will return a tuple of (command_output,
241 exitstatus). If 'withexitstatus' is false then this returns just
242 command_output.
243
244 The run() function can often be used instead of creating a spawn instance.
245 For example, the following code uses spawn::
246
247 from pexpect import *
248 child = spawn('scp foo [email protected]:.')
249 child.expect ('(?i)password')
250 child.sendline (mypassword)
251
252 The previous code can be replace with the following::
253
254 from pexpect import *
255 run ('scp foo [email protected]:.', events={'(?i)password': mypassword})
256
257 Examples
258 ========
259
260 Start the apache daemon on the local machine::
261
262 from pexpect import *
263 run ("/usr/local/apache/bin/apachectl start")
264
265 Check in a file using SVN::
266
267 from pexpect import *
268 run ("svn ci -m 'automatic commit' my_file.py")
269
270 Run a command and capture exit status::
271
272 from pexpect import *
273 (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1)
274
275 Tricky Examples
276 ===============
277
278 The following will run SSH and execute 'ls -l' on the remote machine. The
279 password 'secret' will be sent if the '(?i)password' pattern is ever seen::
280
281 run (
282 "ssh [email protected] 'ls -l'",
283 events={'(?i)password': r'secret\n'}
284 )
285
286 This will start mencoder to rip a video from DVD. This will also display
287 progress ticks every 5 seconds as it runs. For example::
288
289 from pexpect import *
290 def print_ticks(d):
291 print d['event_count'],
292 run (
293 "mencoder dvd://1 -o video.avi -oac copy -ovc copy",
294 events={TIMEOUT:print_ticks},
295 timeout=5
296 )
297
298 The 'events' argument should be a dictionary of patterns and responses.
299 Whenever one of the patterns is seen in the command out run() will send the
300 associated response string. Note that you should put newlines in your
301 string if Enter is necessary. The responses may also contain callback
302 functions. Any callback is function that takes a dictionary as an argument.
303 The dictionary contains all the locals from the run() function, so you can
304 access the child spawn object or any other variable defined in run()
305 (event_count, child, and extra_args are the most useful). A callback may
306 return True to stop the current run process otherwise run() continues until
307 the next event. A callback may also return a string which will be sent to
308 the child. 'extra_args' is not used by directly run(). It provides a way to
309 pass data to a callback function through run() through the locals
310 dictionary passed to a callback."""
311 if timeout == -1:
312 child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
313 else:
314 child = spawn(
315 command, timeout=timeout, maxread=2000, logfile=logfile, cwd=cwd, env=env
316 )
317 if events is not None:
318 patterns = list(events.keys())
319 responses = list(events.values())
320 else:
321 patterns = None # We assume that EOF or TIMEOUT will save us.
322 responses = None
323 child_result_list = []
324 event_count = 0
325 while 1:
326 try:
327 index = child.expect(patterns)
328 if isinstance(child.after, str):
329 child_result_list.append(child.before + child.after)
330 else: # child.after may have been a TIMEOUT or EOF, so don't cat those.
331 child_result_list.append(child.before)
332 if isinstance(responses[index], str):
333 child.send(responses[index])
334 elif callable(responses[index]):
335 callback_result = responses[index](locals())
336 sys.stdout.flush()
337 if isinstance(callback_result, str):
338 child.send(callback_result)
339 elif callback_result:
340 break
341 else:
342 raise TypeError("The callback must be a string or function type.")
343 event_count = event_count + 1
344 except TIMEOUT:
345 child_result_list.append(child.before)
346 break
347 except EOF:
348 child_result_list.append(child.before)
349 break
350 child_result = "".join(child_result_list)
351 if withexitstatus:
352 child.close()
353 return child_result, child.exitstatus
354 return child_result
355
356
357 def spawn(
358 command,
359 args=None,
360 timeout=30,
361 maxread=2000,
362 searchwindowsize=None,
363 logfile=None,
364 cwd=None,
365 env=None,
366 codepage=None,
367 columns=None,
368 rows=None,
369 ):
370 """Create a new spawn instance."""
371 if args is None:
372 args = []
373
374 log("=" * 80)
375 log(f"Buffer size: {maxread}")
376 if searchwindowsize:
377 log(f"Search window size: {searchwindowsize}")
378 log(f"Timeout: {timeout}s")
379 if env:
380 log("Environment:")
381 for name in env:
382 log(f"\t{name}={env[name]}")
383 if cwd:
384 if isinstance(cwd, bytes):
385 cwd = cwd.decode("utf-8")
386 log(f"Working directory: {cwd}")
387 log(f"Spawning {join_args([command, *args])}")
388 if sys.platform == "win32":
389 return SpawnWindows(
390 command,
391 args,
392 timeout,
393 maxread,
394 searchwindowsize,
395 logfile,
396 cwd,
397 env,
398 codepage,
399 columns,
400 rows,
401 )
402 return SpawnUnix(
403 command, args, timeout, maxread, searchwindowsize, logfile, cwd, env
404 )
405
406
407 class SpawnUnix:
408 """The main class interface for Pexpect.
409
410 Use this class to start and control child applications.
411
412 The command parameter may be a string that includes a command and any arguments to
413 the command. For example::
414
415 child = pexpect.spawn('/usr/bin/ftp')
416 child = pexpect.spawn('/usr/bin/ssh [email protected]')
417 child = pexpect.spawn('ls -latr /tmp')
418
419 You may also construct it with a list of arguments like so::
420
421 child = pexpect.spawn('/usr/bin/ftp', [])
422 child = pexpect.spawn('/usr/bin/ssh', ['[email protected]'])
423 child = pexpect.spawn('ls', ['-latr', '/tmp'])
424
425 After this the child application will be created and will be ready to
426 talk to. For normal use, see expect() and send() and sendline().
427
428 Remember that Pexpect does NOT interpret shell meta characters such as
429 redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
430 If you want to run a command and pipe it through another command then
431 you must also start a shell. For example::
432
433 child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
434 child.expect(pexpect.EOF)
435
436 The second form of spawn (where you pass a list of arguments) is useful
437 in situations where you wish to spawn a command and pass it its own
438 argument list. This can make syntax more clear. For example, the
439 following is equivalent to the previous example::
440
441 shell_cmd = 'ls -l | grep LOG > log_list.txt'
442 child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
443 child.expect(pexpect.EOF)
444
445 The maxread attribute sets the read buffer size. This is maximum number
446 of bytes that Pexpect will try to read from a TTY at one time. Setting
447 the maxread size to 1 will turn off buffering. Setting the maxread
448 value higher may help performance in cases where large amounts of
449 output are read back from the child. This feature is useful in
450 conjunction with searchwindowsize.
451
452 The searchwindowsize attribute sets the how far back in the incomming
453 seach buffer Pexpect will search for pattern matches. Every time
454 Pexpect reads some data from the child it will append the data to the
455 incomming buffer. The default is to search from the beginning of the
456 imcomming buffer each time new data is read from the child. But this is
457 very inefficient if you are running a command that generates a large
458 amount of data where you want to match The searchwindowsize does not
459 effect the size of the incomming data buffer. You will still have
460 access to the full buffer after expect() returns.
461
462 The logfile member turns on or off logging. All input and output will
463 be copied to the given file object. Set logfile to None to stop
464 logging. This is the default. Set logfile to sys.stdout to echo
465 everything to standard output. The logfile is flushed after each write.
466
467 Example log input and output to a file::
468
469 child = pexpect.spawn('some_command')
470 fout = file('mylog.txt','w')
471 child.logfile = fout
472
473 Example log to stdout::
474
475 child = pexpect.spawn('some_command')
476 child.logfile = sys.stdout
477
478 The logfile_read and logfile_send members can be used to separately log
479 the input from the child and output sent to the child. Sometimes you
480 don't want to see everything you write to the child. You only want to
481 log what the child sends back. For example::
482
483 child = pexpect.spawn('some_command')
484 child.logfile_read = sys.stdout
485
486 To separately log output sent to the child use logfile_send::
487
488 self.logfile_send = fout
489
490 The delaybeforesend helps overcome a weird behavior that many users
491 were experiencing. The typical problem was that a user would expect() a
492 "Password:" prompt and then immediately call sendline() to send the
493 password. The user would then see that their password was echoed back
494 to them. Passwords don't normally echo. The problem is caused by the
495 fact that most applications print out the "Password" prompt and then
496 turn off stdin echo, but if you send your password before the
497 application turned off echo, then you get your password echoed.
498 Normally this wouldn't be a problem when interacting with a human at a
499 real keyboard. If you introduce a slight delay just before writing then
500 this seems to clear up the problem. This was such a common problem for
501 many users that I decided that the default pexpect behavior should be
502 to sleep just before writing to the child application. 1/20th of a
503 second (50 ms) seems to be enough to clear up the problem. You can set
504 delaybeforesend to 0 to return to the old behavior. Most Linux machines
505 don't like this to be below 0.03. I don't know why.
506
507 Note that spawn is clever about finding commands on your path.
508 It uses the same logic that "which" uses to find executables.
509
510 If you wish to get the exit status of the child you must call the
511 close() method. The exit or signal status of the child will be stored
512 in self.exitstatus or self.signalstatus. If the child exited normally
513 then exitstatus will store the exit return code and signalstatus will
514 be None. If the child was terminated abnormally with a signal then a
515 signalstatus will store the signal value and exitstatus will be None.
516 If you need more detail you can also read the self.status member which
517 stores the status returned by os.waitpid. You can interpret this using
518 os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG.
519 """
520
521 def __init__(
522 self,
523 command,
524 args=None,
525 timeout=30,
526 maxread=2000,
527 searchwindowsize=None,
528 logfile=None,
529 cwd=None,
530 env=None,
531 ):
532 if args is None:
533 args = []
534
535 self.STDIN_FILENO = pty.STDIN_FILENO
536 self.STDOUT_FILENO = pty.STDOUT_FILENO
537 self.STDERR_FILENO = pty.STDERR_FILENO
538 self.stdin = sys.stdin
539 self.stdout = sys.stdout
540 self.stderr = sys.stderr
541
542 self.searcher = None
543 self.ignorecase = False
544 self.before = None
545 self.after = None
546 self.match = None
547 self.match_index = None
548 self.terminated = True
549 self.exitstatus = None
550 self.signalstatus = None
551 self.status = None # status returned by os.waitpid
552 self.flag_eof = False
553 self.pid = None
554 self.child_fd = -1 # initially closed
555 self.timeout = timeout
556 self.delimiter = EOF
557 self.logfile = logfile
558 self.logfile_read = None # input from child (read_nonblocking)
559 self.logfile_send = None # output to send (send, sendline)
560 self.maxread = maxread # max bytes to read at one time into buffer
561 self.buffer = "" # This is the read buffer. See maxread.
562 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. # noqa: E501
563 # Most Linux machines don't like delaybeforesend to be below 0.03 (30 ms).
564 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds. # noqa: E501
565 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds. # noqa: E501
566 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds. # noqa: E501
567 self.softspace = False # File-like object.
568 self.name = f"<{self!r}>" # File-like object.
569 self.encoding = None # File-like object.
570 self.closed = True # File-like object.
571 self.ocwd = os.getcwd()
572 self.cwd = cwd
573 self.env = env
574 self.__irix_hack = (
575 sys.platform.lower().find("irix") >= 0
576 ) # This flags if we are running on irix
577 # Solaris uses internal __fork_pty(). All others use pty.fork().
578 if (sys.platform.lower().find("solaris") >= 0) or (
579 sys.platform.lower().find("sunos5") >= 0
580 ):
581 self.use_native_pty_fork = False
582 else:
583 self.use_native_pty_fork = True
584
585 # allow dummy instances for subclasses that may not use command or args.
586 if command is None:
587 self.command = None
588 self.args = None
589 self.name = "<pexpect factory incomplete>"
590 else:
591 self._spawn(command, args)
592
593 def __del__(self):
594 """Make sure that no system resources are left open.
595
596 Python only garbage collects Python objects. OS file descriptors are
597 not Python objects, so they must be handled explicitly. If the child
598 file descriptor was opened outside this class (passed to the
599 constructor) then this does not close it.
600 """
601 if not self.closed:
602 # It is possible for __del__ methods to execute during the
603 # teardown of the Python VM itself. Thus, self.close() may
604 # trigger an exception because os.close may be None.
605 # -- Fernando Perez
606 with contextlib.suppress(AttributeError):
607 self.close()
608
609 def __str__(self):
610 """Return a human-readable string that represents the state of the object."""
611 s = []
612 s.append(repr(self))
613 s.append("version: " + __version__ + " (" + __revision__ + ")")
614 s.append("command: " + str(self.command))
615 s.append("args: " + str(self.args))
616 s.append("searcher: " + str(self.searcher))
617 s.append("buffer (last 100 chars): " + str(self.buffer)[-100:])
618 s.append("before (last 100 chars): " + str(self.before)[-100:])
619 s.append("after: " + str(self.after))
620 s.append("match: " + str(self.match))
621 s.append("match_index: " + str(self.match_index))
622 s.append("exitstatus: " + str(self.exitstatus))
623 s.append("flag_eof: " + str(self.flag_eof))
624 s.append("pid: " + str(self.pid))
625 s.append("child_fd: " + str(self.child_fd))
626 s.append("closed: " + str(self.closed))
627 s.append("timeout: " + str(self.timeout))
628 s.append("delimiter: " + str(self.delimiter))
629 s.append("logfile: " + str(self.logfile))
630 s.append("logfile_read: " + str(self.logfile_read))
631 s.append("logfile_send: " + str(self.logfile_send))
632 s.append("maxread: " + str(self.maxread))
633 s.append("ignorecase: " + str(self.ignorecase))
634 s.append("searchwindowsize: " + str(self.searchwindowsize))
635 s.append("delaybeforesend: " + str(self.delaybeforesend))
636 s.append("delayafterclose: " + str(self.delayafterclose))
637 s.append("delayafterterminate: " + str(self.delayafterterminate))
638 return "\n".join(s)
639
640 def _spawn(self, command, args=None):
641 """Start the given command in a child process.
642
643 This does all the fork/exec type of stuff for a pty. This is called by
644 __init__. If args is empty then command will be parsed (split on
645 spaces) and args will be set to parsed arguments.
646 """
647 if args is None:
648 args = []
649
650 # The pid and child_fd of this object get set by this method.
651 # Note that it is difficult for this method to fail.
652 # You cannot detect if the child process cannot start.
653 # So the only way you can tell if the child process started
654 # or not is to try to read from the file descriptor. If you get
655 # EOF immediately then it means that the child is already dead.
656 # That may not necessarily be bad because you may haved spawned a child
657 # that performs some task; creates no stdout output; and then dies.
658
659 # If command is an int type then it may represent a file descriptor.
660 if isinstance(command, int):
661 raise ExceptionPexpect(
662 "Command is an int type. "
663 "If this is a file descriptor "
664 "then maybe you want to use fdpexpect.fdspawn "
665 "which takes an existing file descriptor "
666 "instead of a command string."
667 )
668
669 if not isinstance(args, list):
670 raise TypeError("The argument, args, must be a list.")
671
672 if not args:
673 self.args = split_command_line(command)
674 self.command = self.args[0]
675 else:
676 self.args = args[:] # work with a copy
677 self.args.insert(0, command)
678 self.command = command
679
680 command_with_path = which(self.command)
681 if command_with_path is None:
682 raise ExceptionPexpect(
683 f"The command was not found or was not executable: {self.command}."
684 )
685 self.command = command_with_path
686 self.args[0] = self.command
687
688 new_args = []
689 for arg in self.args:
690 if isinstance(arg, bytes):
691 arg = arg.decode()
692 new_args.append(arg)
693 self.args = new_args
694
695 self.name = "<" + " ".join(self.args) + ">"
696
697 if self.pid is not None:
698 raise ValueError("The pid member should be None.")
699 if self.command is None:
700 raise ValueError("The command member should not be None.")
701
702 if self.use_native_pty_fork:
703 try:
704 self.pid, self.child_fd = pty.fork()
705 except OSError as e:
706 raise ExceptionPexpect(f"Error! pty.fork() failed: {e}") from e
707 else: # Use internal __fork_pty
708 self.pid, self.child_fd = self.__fork_pty()
709
710 if self.pid == 0: # Child
711 with contextlib.suppress(Exception):
712 self.child_fd = sys.stdout.fileno() # used by setwinsize()
713 self.setwinsize(24, 80)
714 # Some platforms do not like setwinsize (Cygwin).
715 # This will cause problem when running applications that
716 # are very picky about window size.
717 # This is a serious limitation, but not a show stopper.
718 # Do not allow child to inherit open file descriptors from parent.
719 max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
720 for i in range(3, max_fd):
721 with contextlib.suppress(OSError):
722 os.close(i)
723
724 # I don't know why this works, but ignoring SIGHUP fixes a
725 # problem when trying to start a Java daemon with sudo
726 # (specifically, Tomcat).
727 signal.signal(signal.SIGHUP, signal.SIG_IGN)
728
729 if self.cwd is not None:
730 os.chdir(self.cwd)
731 try:
732 if self.env is None:
733 os.execv(self.command, self.args) # noqa: S606
734 else:
735 os.execvpe(self.command, self.args, self.env) # noqa: S606
736 finally:
737 if self.cwd is not None:
738 # Restore the original working dir
739 os.chdir(self.ocwd)
740
741 # Parent
742 self.terminated = False
743 self.closed = False
744
745 def __fork_pty(self):
746 """Implement a substitute for the forkpty system call.
747
748 This should be more portable than the pty.fork() function.
749 Specifically, this should work on Solaris.
750
751 Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
752 resolve the issue with Python's pty.fork() not supporting Solaris,
753 particularly ssh. Based on patch to posixmodule.c authored by Noah
754
755 Spurrier:
756
757 http://mail.python.org/pipermail/python-dev/2003-May/035281.html
758
759 """
760 parent_fd, child_fd = os.openpty()
761 if parent_fd < 0 or child_fd < 0:
762 raise ExceptionPexpect("Error! Could not open pty with os.openpty().")
763
764 pid = os.fork()
765 if pid < 0:
766 raise ExceptionPexpect("Error! Failed os.fork().")
767 if pid == 0:
768 # Child.
769 os.close(parent_fd)
770 self.__pty_make_controlling_tty(child_fd)
771
772 os.dup2(child_fd, 0)
773 os.dup2(child_fd, 1)
774 os.dup2(child_fd, 2)
775
776 if child_fd > 2:
777 os.close(child_fd)
778 else:
779 # Parent.
780 os.close(child_fd)
781
782 return pid, parent_fd
783
784 def __pty_make_controlling_tty(self, tty_fd):
785 """Make the pseudo-terminal the controlling tty.
786
787 This should be more portable than the pty.fork() function.
788 Specifically, this should work on Solaris.
789 """
790 child_name = os.ttyname(tty_fd)
791
792 # Disconnect from controlling tty if still connected.
793 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
794 if fd >= 0:
795 os.close(fd)
796
797 os.setsid()
798
799 # Verify we are disconnected from controlling tty
800 try:
801 fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
802 if fd >= 0:
803 os.close(fd)
804 raise ExceptionPexpect(
805 "Error! We are not disconnected from a controlling tty."
806 )
807 except Exception:
808 # Good! We are disconnected from a controlling tty.
809 pass
810
811 # Verify we can open child pty.
812 fd = os.open(child_name, os.O_RDWR)
813 if fd < 0:
814 raise ExceptionPexpect("Error! Could not open child pty, " + child_name)
815 os.close(fd)
816
817 # Verify we now have a controlling tty.
818 fd = os.open("/dev/tty", os.O_WRONLY)
819 if fd < 0:
820 raise ExceptionPexpect("Error! Could not open controlling tty, /dev/tty")
821 os.close(fd)
822
823 def fileno(self): # File-like object.
824 """Return the file descriptor of the pty for the child."""
825 return self.child_fd
826
827 def close(self, force=True): # File-like object.
828 """Close the connection with the child application.
829
830 Note that calling close() more than once is valid. This emulates
831 standard Python behavior with files. Set force to True if you want to
832 make sure that the child is terminated (SIGKILL is sent if the child
833 ignores SIGHUP and SIGINT).
834 """
835 if not self.closed:
836 self.flush()
837 os.close(self.child_fd)
838 time.sleep(
839 self.delayafterclose
840 ) # Give kernel time to update process status.
841 if self.isalive() and not self.terminate(force):
842 raise ExceptionPexpect(
843 "close() could not terminate the child using terminate()"
844 )
845 self.child_fd = -1
846 self.closed = True
847 # self.pid = None
848
849 def flush(self): # File-like object.
850 """Do nothing.
851
852 It is here to support the interface for a File-like object.
853 """
854
855 def isatty(self): # File-like object.
856 """Return True if fd is open and is a tty."""
857 return os.isatty(self.child_fd)
858
859 def waitnoecho(self, timeout=-1):
860 """Wait until the terminal ECHO flag is set False.
861
862 This returns True if the echo mode is off. This returns False if the
863 ECHO flag was not set False before the timeout. This can be used to
864 detect when the child is waiting for a password. Usually a child
865 application will turn off echo mode when it is waiting for the user to
866 enter a password. For example, instead of expecting the "password:"
867 prompt you can wait for the child to set ECHO off:
868
869 p = pexpect.spawn ('ssh [email protected]')
870 p.waitnoecho()
871 p.sendline(mypassword)
872
873 If timeout is None then this method to block forever until ECHO flag is
874 False.
875
876 """
877 end_time = -1
878 if timeout == -1:
879 timeout = self.timeout
880 if timeout is not None:
881 end_time = time.time() + timeout
882 while True:
883 if not self.getecho():
884 return True
885 if timeout < 0 and timeout is not None:
886 return False
887 if timeout is not None:
888 timeout = end_time - time.time()
889 time.sleep(0.1)
890
891 def getecho(self):
892 """Return the terminal echo mode.
893
894 This returns True if echo is on or False if echo is off. Child
895 applications that are expecting you to enter a password often set ECHO
896 False. See waitnoecho().
897 """
898 attr = termios.tcgetattr(self.child_fd)
899 return bool(attr[3] & termios.ECHO)
900
901 def setecho(self, state):
902 """Set the terminal echo mode on or off.
903
904 Note that anything the child sent before the echo will be lost, so you
905 should be sure that your input buffer is empty before you call
906 setecho(). For example, the following will work as expected:
907
908 p = pexpect.spawn('cat')
909 # We will see this twice (once from tty echo and again from cat).
910 p.sendline ('1234')
911 p.expect (['1234'])
912 p.expect (['1234'])
913 p.setecho(False) # Turn off tty echo
914 p.sendline ('abcd') # We will set this only once (echoed by cat).
915 p.sendline ('wxyz') # We will set this only once (echoed by cat)
916 p.expect (['abcd'])
917 p.expect (['wxyz'])
918
919 The following WILL NOT WORK because the lines sent before the setecho
920 will be lost::
921
922 p = pexpect.spawn('cat')
923 # We will see this twice (once from tty echo and again from cat).
924 p.sendline ('1234')
925 p.setecho(False) # Turn off tty echo
926 p.sendline ('abcd') # We will set this only once (echoed by cat).
927 p.sendline ('wxyz') # We will set this only once (echoed by cat)
928 p.expect (['1234'])
929 p.expect (['1234'])
930 p.expect (['abcd'])
931 p.expect (['wxyz'])
932 """
933 attr = termios.tcgetattr(self.child_fd)
934 if state:
935 attr[3] = attr[3] | termios.ECHO
936 else:
937 attr[3] = attr[3] & ~termios.ECHO
938 # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent
939 # and blocked on some platforms. TCSADRAIN is probably ideal if it worked.
940 termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
941
942 def read_nonblocking(self, size=1, timeout=-1):
943 """Read at most size characters from the child application.
944
945 It includes a timeout. If the read does not complete within the timeout
946 period then a TIMEOUT exception is raised. If the end of file is read
947 then an EOF exception will be raised. If a log file was set using
948 setlog() then all data will also be written to the log file.
949
950 If timeout is None then the read may block indefinitely. If timeout is
951 -1 then the self.timeout value is used. If timeout is 0 then the child
952 is polled and if there was no data immediately ready then this will
953 raise a TIMEOUT exception.
954
955 The timeout refers only to the amount of time to read at least one
956 character. This is not effected by the 'size' parameter, so if you call
957 read_nonblocking(size=100, timeout=30) and only one character is
958 available right away then one character will be returned immediately.
959 It will not wait for 30 seconds for another 99 characters to come in.
960
961 This is a wrapper around os.read(). It uses select.select() to
962 implement the timeout.
963 """
964 if self.closed:
965 raise ValueError("I/O operation on closed file in read_nonblocking().")
966
967 if timeout == -1:
968 timeout = self.timeout
969
970 # Note that some systems such as Solaris do not give an EOF when
971 # the child dies. In fact, you can still try to read
972 # from the child_fd -- it will block forever or until TIMEOUT.
973 # For this case, I test isalive() before doing any reading.
974 # If isalive() is false, then I pretend that this is the same as EOF.
975 if not self.isalive():
976 r, w, e = self.__select(
977 [self.child_fd], [], [], 0
978 ) # timeout of 0 means "poll"
979 if not r:
980 self.flag_eof = True
981 raise EOF(
982 "End Of File (EOF) in read_nonblocking(). Braindead platform."
983 )
984 elif self.__irix_hack:
985 # This is a hack for Irix.
986 # It seems that Irix requires a long delay before checking isalive.
987 # This adds a 2 second delay, but only when the child is terminated.
988 r, w, e = self.__select([self.child_fd], [], [], 2)
989 if not r and not self.isalive():
990 self.flag_eof = True
991 raise EOF("End Of File (EOF) in read_nonblocking(). Pokey platform.")
992
993 r, w, e = self.__select([self.child_fd], [], [], timeout)
994
995 if not r:
996 if not self.isalive():
997 # Some platforms, such as Irix,
998 # will claim that their processes are alive;
999 # then timeout on the select;
1000 # and then finally admit that they are not alive.
1001 self.flag_eof = True
1002 raise EOF(
1003 "End of File (EOF) in read_nonblocking(). Very pokey platform."
1004 )
1005 raise TIMEOUT("Timeout exceeded in read_nonblocking().")
1006
1007 if self.child_fd in r:
1008 try:
1009 s = os.read(self.child_fd, size)
1010 except OSError as e: # Linux does this
1011 self.flag_eof = True
1012 raise EOF(
1013 "End Of File (EOF) in read_nonblocking(). Exception style platform."
1014 ) from e
1015 if s == b"": # BSD style
1016 self.flag_eof = True
1017 raise EOF(
1018 "End Of File (EOF) in read_nonblocking(). "
1019 "Empty string style platform."
1020 )
1021
1022 if self.logfile is not None:
1023 self.logfile.write(s)
1024 self.logfile.flush()
1025 if self.logfile_read is not None:
1026 self.logfile_read.write(s)
1027 self.logfile_read.flush()
1028
1029 return s
1030
1031 raise ExceptionPexpect("Reached an unexpected state in read_nonblocking().")
1032
1033 def read(self, size=-1): # File-like object.
1034 """Read at most "size" bytes from the file.
1035
1036 Read less if the read hits EOF before obtaining size bytes).
1037
1038 If the size argument is negative or
1039 omitted, read all data until EOF is reached. The bytes are returned as
1040 a string object. An empty string is returned when EOF is encountered
1041 immediately."""
1042 if size == 0:
1043 return ""
1044 if size < 0:
1045 self.expect(self.delimiter) # delimiter default is EOF
1046 return self.before
1047
1048 # I could have done this more directly by not using expect(), but
1049 # I deliberately decided to couple read() to expect() so that
1050 # I would catch any bugs early and ensure consistant behavior.
1051 # It's a little less efficient, but there is less for me to
1052 # worry about if I have to later modify read() or expect().
1053 # Note, it's OK if size==-1 in the regex. That just means it
1054 # will never match anything in which case we stop only on EOF.
1055 cre = re.compile(rf".{{{size}}}", re.DOTALL)
1056 index = self.expect([cre, self.delimiter]) # delimiter default is EOF
1057 if index == 0:
1058 return self.after # self.before should be ''. Should I assert this?
1059 return self.before
1060
1061 def readline(self, size=-1): # File-like object.
1062 r"""Read and returns one entire line.
1063
1064 A trailing newline is kept in the string, but may be absent when a file
1065 ends with an incomplete line. Note: This readline() looks for a \r\n
1066 pair even on UNIX because this is what the pseudo tty device returns.
1067 So contrary to what you may expect you will receive the newline as
1068 \r\n. An empty string is returned when EOF is hit immediately.
1069 Currently, the size argument is mostly ignored, so this behavior is not
1070 standard for a file-like object. If size is 0 then an empty string is
1071 returned.
1072 """
1073 if size == 0:
1074 return ""
1075 index = self.expect(["\r\n", self.delimiter]) # delimiter default is EOF
1076 if index == 0:
1077 return self.before + "\r\n"
1078 return self.before
1079
1080 def __iter__(self) -> Self: # File-like object.
1081 """Support iterators over a file-like object."""
1082 return self
1083
1084 def __next__(self): # File-like object.
1085 """Support iterators over a file-like object."""
1086 result = self.readline()
1087 if result == "":
1088 raise StopIteration
1089 return result
1090
1091 def readlines(self, sizehint=-1): # File-like object.
1092 """Read until EOF using readline().
1093
1094 Return a list containing the lines thus read. The optional "sizehint" argument
1095 is ignored.
1096 """
1097 lines = []
1098 while True:
1099 line = self.readline()
1100 if not line:
1101 break
1102 lines.append(line)
1103 return lines
1104
1105 def write(self, s): # File-like object.
1106 """Similar to send() except that there is no return value."""
1107 self.send(s)
1108
1109 def writelines(self, sequence): # File-like object.
1110 """Call write() for each element in the sequence.
1111
1112 The sequence can be any iterable object producing strings, typically a
1113 list of strings. This does not add line separators There is no return
1114 value.
1115 """
1116 for s in sequence:
1117 self.write(s)
1118
1119 def send(self, s):
1120 """Send a string to the child process.
1121
1122 This returns the number of bytes written. If a log file was set then
1123 the data is also written to the log.
1124 """
1125 time.sleep(self.delaybeforesend)
1126 if self.logfile is not None:
1127 self.logfile.write(s)
1128 self.logfile.flush()
1129 if self.logfile_send is not None:
1130 self.logfile_send.write(s)
1131 self.logfile_send.flush()
1132 if not isinstance(s, bytes):
1133 if not isinstance(s, str):
1134 s = str(s)
1135 s = s.encode("utf-8")
1136 return os.write(self.child_fd, s)
1137
1138 def sendline(self, s=""):
1139 """Like send(), but it add a line feed (os.linesep).
1140
1141 This returns the number of bytes written."""
1142 return self.send(s) + self.send(os.linesep)
1143
1144 def sendcontrol(self, char):
1145 """Send a control character to the child such as Ctrl-C or Ctrl-D.
1146
1147 For example, to send a Ctrl-G (ASCII 7):
1148
1149 child.sendcontrol('g')
1150
1151 See also, sendintr() and sendeof().
1152 """
1153 char = char.lower()
1154 a = ord(char)
1155 if 97 <= a <= 122:
1156 a = a - ord("a") + 1
1157 return self.send(chr(a))
1158 d = {
1159 "@": 0,
1160 "`": 0,
1161 "[": 27,
1162 "{": 27,
1163 "\\": 28,
1164 "|": 28,
1165 "]": 29,
1166 "}": 29,
1167 "^": 30,
1168 "~": 30,
1169 "_": 31,
1170 "?": 127,
1171 }
1172 if char not in d:
1173 return 0
1174 return self.send(chr(d[char]))
1175
1176 def sendeof(self):
1177 """Send an EOF to the child.
1178
1179 This sends a character which causes the pending parent output buffer to
1180 be sent to the waiting child program without waiting for end-of-line.
1181 If it is the first character of the line, the read() in the user
1182 program returns 0, which signifies end-of-file. This means to work as
1183 expected a sendeof() has to be called at the beginning of a line. This
1184 method does not send a newline. It is the responsibility of the caller
1185 to ensure the eof is sent at the beginning of a line.
1186 """
1187 # # Hmmm... how do I send an EOF?
1188 # #C if ((m = write(pty, *buf, p - *buf)) < 0)
1189 # #C return (errno == EWOULDBLOCK) ? n : -1;
1190 # fd = sys.stdin.fileno()
1191 # old = termios.tcgetattr(fd) # remember current state
1192 # attr = termios.tcgetattr(fd)
1193 # attr[3] = attr[3] | termios.ICANON # ICANON must be set to recognize EOF
1194 # try: # use try/finally to ensure state gets restored
1195 # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
1196 # if hasattr(termios, 'CEOF'):
1197 # os.write (self.child_fd, '%c' % termios.CEOF)
1198 # else:
1199 # # Silly platform does not define CEOF so assume CTRL-D
1200 # os.write (self.child_fd, '%c' % 4)
1201 # finally: # restore state
1202 # termios.tcsetattr(fd, termios.TCSADRAIN, old)
1203 if hasattr(termios, "VEOF"):
1204 char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
1205 else:
1206 # platform does not define VEOF so assume CTRL-D
1207 char = chr(4)
1208 self.send(char)
1209
1210 def sendintr(self):
1211 """Send a SIGINT to the child.
1212
1213 It does not require the SIGINT to be the first character on a line.
1214 """
1215 if hasattr(termios, "VINTR"):
1216 char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
1217 else:
1218 # platform does not define VINTR so assume CTRL-C
1219 char = chr(3)
1220 self.send(char)
1221
1222 def eof(self):
1223 """Return True if the EOF exception was ever raised."""
1224 return self.flag_eof
1225
1226 def terminate(self, force=False):
1227 """Force a child process to terminate.
1228
1229 It starts nicely with SIGHUP and SIGINT. If "force" is True then moves
1230 onto SIGKILL. This returns True if the child was terminated. This
1231 returns False if the child could not be terminated.
1232 """
1233 if not self.isalive():
1234 return True
1235 try:
1236 self.kill(signal.SIGHUP)
1237 time.sleep(self.delayafterterminate)
1238 if not self.isalive():
1239 return True
1240 self.kill(signal.SIGCONT)
1241 time.sleep(self.delayafterterminate)
1242 if not self.isalive():
1243 return True
1244 self.kill(signal.SIGINT)
1245 time.sleep(self.delayafterterminate)
1246 if not self.isalive():
1247 return True
1248 if force:
1249 self.kill(signal.SIGKILL)
1250 time.sleep(self.delayafterterminate)
1251 return self.isalive()
1252 return False
1253 except OSError:
1254 # I think there are kernel timing issues that sometimes cause
1255 # this to happen. I think isalive() reports True, but the
1256 # process is dead to the kernel.
1257 # Make one last attempt to see if the kernel is up to date.
1258 time.sleep(self.delayafterterminate)
1259 return not self.isalive()
1260
1261 def wait(self):
1262 """Wait until the child exits.
1263
1264 This is a blocking call. This will not read any data from the child, so
1265 this will block forever if the child has unread output and has
1266 terminated. In other words, the child may have printed output then
1267 called exit(); but, technically, the child is still alive until its
1268 output is read.
1269 """
1270 if self.isalive():
1271 pid, status = os.waitpid(self.pid, 0)
1272 else:
1273 raise ExceptionPexpect("Cannot wait for dead child process.")
1274 self.exitstatus = os.WEXITSTATUS(status)
1275 if os.WIFEXITED(status):
1276 self.status = status
1277 self.exitstatus = os.WEXITSTATUS(status)
1278 self.signalstatus = None
1279 self.terminated = True
1280 elif os.WIFSIGNALED(status):
1281 self.status = status
1282 self.exitstatus = None
1283 self.signalstatus = os.WTERMSIG(status)
1284 self.terminated = True
1285 elif os.WIFSTOPPED(status):
1286 raise ExceptionPexpect(
1287 "Wait was called for a child process that is stopped. "
1288 "This is not supported. Is some other process attempting job "
1289 "control with our child pid?"
1290 )
1291 return self.exitstatus
1292
1293 def isalive(self):
1294 """Test if the child process is running or not.
1295
1296 This is non-blocking. If the child was terminated then this will read
1297 the exitstatus or signalstatus of the child. This returns True if the
1298 child process appears to be running or False if not. It can take
1299 literally SECONDS for Solaris to return the right status.
1300 """
1301 if self.terminated:
1302 return False
1303
1304 # This is for Linux, which requires the blocking form of waitpid to get
1305 # status of a defunct process. This is super-lame. The flag_eof would have
1306 # been set in read_nonblocking(), so this should be safe.
1307 waitpid_options = 0 if self.flag_eof else os.WNOHANG
1308
1309 try:
1310 pid, status = os.waitpid(self.pid, waitpid_options)
1311 except OSError as e: # No child processes
1312 if e.args[0] == str(errno.ECHILD):
1313 raise ExceptionPexpect(
1314 'isalive() encountered condition where "terminated" is 0, '
1315 "but there was no child process. "
1316 "Did someone else call waitpid() on our process?"
1317 ) from e
1318 raise e
1319
1320 # I have to do this twice for Solaris.
1321 # I can't even believe that I figured this out...
1322 # If waitpid() returns 0 it means that no child process wishes to
1323 # report, and the value of status is undefined.
1324 if pid == 0:
1325 try:
1326 pid, status = os.waitpid(
1327 self.pid, waitpid_options
1328 ) # os.WNOHANG) # Solaris!
1329 except OSError as e: # This should never happen...
1330 if e.args[0] == str(errno.ECHILD):
1331 raise ExceptionPexpect(
1332 "isalive() encountered condition that should never happen. "
1333 "There was no child process. "
1334 "Did someone else call waitpid() on our process?"
1335 ) from e
1336 raise e
1337
1338 # If pid is still 0 after two calls to waitpid() then
1339 # the process really is alive. This seems to work on all platforms,
1340 # except for Irix which seems to require a blocking call on waitpid
1341 # or select, so I let read_nonblocking take care of this situation
1342 # (unfortunately, this requires waiting through the timeout).
1343 if pid == 0:
1344 return True
1345
1346 if pid == 0:
1347 return True
1348
1349 if os.WIFEXITED(status):
1350 self.status = status
1351 self.exitstatus = os.WEXITSTATUS(status)
1352 self.signalstatus = None
1353 self.terminated = True
1354 elif os.WIFSIGNALED(status):
1355 self.status = status
1356 self.exitstatus = None
1357 self.signalstatus = os.WTERMSIG(status)
1358 self.terminated = True
1359 elif os.WIFSTOPPED(status):
1360 raise ExceptionPexpect(
1361 "isalive() encountered condition where child process is "
1362 "stopped. This is not supported. Is some other process "
1363 "attempting job control with our child pid?"
1364 )
1365 return False
1366
1367 def kill(self, sig):
1368 """Send the given signal to the child application.
1369
1370 In keeping with UNIX tradition it has a misleading name. It does not
1371 necessarily kill the child unless you send the right signal.
1372 """
1373 # Same as os.kill, but the pid is given for you.
1374 if self.isalive():
1375 os.kill(self.pid, sig)
1376
1377 def compile_pattern_list(self, patterns):
1378 """Compile a pattern-string or a list of pattern-strings.
1379
1380 Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
1381 those. Patterns may also be None which results in an empty list (you
1382 might do this if waiting for an EOF or TIMEOUT condition without
1383 expecting any pattern).
1384
1385 This is used by expect() when calling expect_list(). Thus expect() is
1386 nothing more than::
1387
1388 cpl = self.compile_pattern_list(pl)
1389 return self.expect_list(cpl, timeout)
1390
1391 If you are using expect() within a loop it may be more
1392 efficient to compile the patterns first and then call expect_list().
1393 This avoid calls in a loop to compile_pattern_list()::
1394
1395 cpl = self.compile_pattern_list(my_pattern)
1396 while some_condition:
1397 ...
1398 i = self.expect_list(clp, timeout)
1399 ...
1400 """
1401 if patterns is None:
1402 return []
1403 if not isinstance(patterns, list):
1404 patterns = [patterns]
1405
1406 compile_flags = re.DOTALL # Allow dot to match \n
1407 if self.ignorecase:
1408 compile_flags = compile_flags | re.IGNORECASE
1409 compiled_pattern_list = []
1410 for p in patterns:
1411 if isinstance(p, str):
1412 compiled_pattern_list.append(re.compile(p, compile_flags))
1413 elif p is EOF:
1414 compiled_pattern_list.append(EOF)
1415 elif p is TIMEOUT:
1416 compiled_pattern_list.append(TIMEOUT)
1417 elif isinstance(p, re.Pattern):
1418 compiled_pattern_list.append(p)
1419 else:
1420 raise TypeError(
1421 "Argument must be one of StringTypes, EOF, TIMEOUT, "
1422 f"SRE_Pattern, or a list of those type. {type(p)}"
1423 )
1424
1425 return compiled_pattern_list
1426
1427 def expect(self, pattern, timeout=-1, searchwindowsize=None):
1428 """Seek through the stream until a pattern is matched.
1429
1430 The pattern is overloaded and may take several types. The pattern can be a
1431 StringType, EOF, a compiled re, or a list of any of those types. Strings will be
1432 compiled to re types.
1433
1434 This returns the index into the pattern list. If the pattern was not a list this
1435 returns index 0 on a successful match. This may raise exceptions for EOF or
1436 TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the
1437 pattern list. That will cause expect to match an EOF or TIMEOUT condition
1438 instead of raising an exception.
1439
1440 If you pass a list of patterns and more than one matches, the first match in the
1441 stream is chosen. If more than one pattern matches at that point, the leftmost
1442 in the pattern list is chosen. For example::
1443
1444 # the input is 'foobar'
1445 index = p.expect (['bar', 'foo', 'foobar'])
1446 # returns 1 ('foo') even though 'foobar' is a "better" match
1447
1448 Please note, however, that buffering can affect this behavior, since input
1449 arrives in unpredictable chunks. For example::
1450
1451 # the input is 'foobar'
1452 index = p.expect (['foobar', 'foo'])
1453 # returns 0 ('foobar') if all input is available at once,
1454 # but returs 1 ('foo') if parts of the final 'bar' arrive late
1455
1456 After a match is found the instance attributes 'before', 'after' and 'match'
1457 will be set. You can see all the data read before the match in 'before'. You can
1458 see the data that was matched in 'after'. The re.MatchObject used in the re
1459 match will be in 'match'. If an error occurred then 'before' will be set to all
1460 the data read so far and 'after' and 'match' will be None.
1461
1462 If timeout is -1 then timeout will be set to the self.timeout value.
1463
1464 A list entry may be EOF or TIMEOUT instead of a string. This will catch these
1465 exceptions and return the index of the list entry instead of raising the
1466 exception. The attribute 'after' will be set to the exception type. The
1467 attribute 'match' will be None. This allows you to write code like this::
1468
1469 index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
1470 if index == 0:
1471 do_something()
1472 elif index == 1:
1473 do_something_else()
1474 elif index == 2:
1475 do_some_other_thing()
1476 elif index == 3:
1477 do_something_completely_different()
1478
1479 instead of code like this::
1480
1481 try:
1482 index = p.expect (['good', 'bad'])
1483 if index == 0:
1484 do_something()
1485 elif index == 1:
1486 do_something_else()
1487 except EOF:
1488 do_some_other_thing()
1489 except TIMEOUT:
1490 do_something_completely_different()
1491
1492 These two forms are equivalent. It all depends on what you want. You can also
1493 just expect the EOF if you are waiting for all output of a child to finish. For
1494 example::
1495
1496 p = pexpect.spawn('/bin/ls')
1497 p.expect (pexpect.EOF)
1498 print p.before
1499
1500 If you are trying to optimize for speed then see expect_list().
1501 """
1502 compiled_pattern_list = self.compile_pattern_list(pattern)
1503 return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
1504
1505 def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1):
1506 """Return the index into the pattern_list that matched the child output.
1507
1508 The list may also contain EOF or TIMEOUT (which are not compiled regular
1509 expressions). This method is similar to the expect() method except that
1510 expect_list() does not recompile the pattern list on every call. This may help
1511 if you are trying to optimize for speed, otherwise just use the expect() method.
1512 This is called by expect(). If timeout==-1 then the self.timeout value is used.
1513 If searchwindowsize==-1 then the self.searchwindowsize value is used.
1514 """
1515 return self.expect_loop(SearcherRegex(pattern_list), timeout, searchwindowsize)
1516
1517 def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1):
1518 """Similar to expect().
1519
1520 But use plain string matching instead of compiled regular expressions
1521 in 'pattern_list'. The 'pattern_list' may be a string; a list or other
1522 sequence of strings; or TIMEOUT and EOF.
1523
1524 This call might be faster than expect() for two reasons: string
1525 searching is faster than RE matching, and it is possible to limit the
1526 search to just the end of the input buffer.
1527
1528 This method is also useful when you don't want to have to worry about
1529 escaping regular expression characters that you want to match."""
1530 if isinstance(pattern_list, str) or pattern_list in (TIMEOUT, EOF):
1531 pattern_list = [pattern_list]
1532 return self.expect_loop(SearcherString(pattern_list), timeout, searchwindowsize)
1533
1534 def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
1535 """The common loop used inside expect.
1536
1537 The 'searcher' should be an instance of SearcherRegex or SearcherString, which
1538 describes how and what to search for in the input.
1539
1540 See expect() for other arguments, return value and exceptions.
1541 """
1542 self.searcher = searcher
1543
1544 end_time = -1
1545 if timeout == -1:
1546 timeout = self.timeout
1547 if timeout is not None:
1548 end_time = time.time() + timeout
1549 if searchwindowsize == -1:
1550 searchwindowsize = self.searchwindowsize
1551
1552 incoming = ""
1553 try:
1554 incoming = self.buffer
1555 freshlen = len(incoming)
1556 while True: # Keep reading until exception or return.
1557 index = searcher.search(incoming, freshlen, searchwindowsize)
1558 if index >= 0:
1559 self.buffer = incoming[searcher.end :]
1560 self.before = incoming[: searcher.start]
1561 self.after = incoming[searcher.start : searcher.end]
1562 self.match = searcher.match
1563 self.match_index = index
1564 return self.match_index
1565 # No match at this point
1566 if timeout < 0 and timeout is not None:
1567 raise TIMEOUT("Timeout exceeded in expect_any().")
1568 # Still have time left, so read more data
1569 c = self.read_nonblocking(self.maxread, timeout)
1570 freshlen = len(c)
1571 time.sleep(0.0001)
1572 if sys.platform == "win32":
1573 incoming += c
1574 else:
1575 incoming += c.decode()
1576 if timeout is not None:
1577 timeout = end_time - time.time()
1578 except EOF as e:
1579 self.buffer = ""
1580 self.before = incoming
1581 self.after = EOF
1582 index = searcher.eof_index
1583 if index >= 0:
1584 self.match = EOF
1585 self.match_index = index
1586 return self.match_index
1587 self.match = None
1588 self.match_index = None
1589 raise EOF(str(e) + "\n" + str(self)) from e
1590 except TIMEOUT as e:
1591 self.buffer = incoming
1592 self.before = incoming
1593 self.after = TIMEOUT
1594 index = searcher.timeout_index
1595 if index >= 0:
1596 self.match = TIMEOUT
1597 self.match_index = index
1598 return self.match_index
1599 self.match = None
1600 self.match_index = None
1601 raise TIMEOUT(str(e) + "\n" + str(self)) from e
1602 except Exception:
1603 self.before = incoming
1604 self.after = None
1605 self.match = None
1606 self.match_index = None
1607 raise
1608
1609 def getwinsize(self):
1610 """Return the terminal window size of the child tty.
1611
1612 The return value is a tuple of (rows, cols).
1613 """
1614 TIOCGWINSZ = getattr(termios, "TIOCGWINSZ", 1074295912)
1615 s = struct.pack("HHHH", 0, 0, 0, 0)
1616 x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
1617 return struct.unpack("HHHH", x)[0:2]
1618
1619 def setwinsize(self, r, c):
1620 """Set the terminal window size of the child tty.
1621
1622 This will cause a SIGWINCH signal to be sent to the child. This does
1623 not change the physical window size. It changes the size reported to
1624 TTY-aware applications like vi or curses -- applications that respond
1625 to the SIGWINCH signal.
1626 """
1627 # Check for buggy platforms. Some Python versions on some platforms
1628 # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
1629 # termios.TIOCSWINSZ. It is not clear why this happens.
1630 # These platforms don't seem to handle the signed int very well;
1631 # yet other platforms like OpenBSD have a large negative value for
1632 # TIOCSWINSZ and they don't have a truncate problem.
1633 # Newer versions of Linux have totally different values for TIOCSWINSZ.
1634 # Note that this fix is a hack.
1635 TIOCSWINSZ = getattr(termios, "TIOCSWINSZ", -2146929561)
1636 if TIOCSWINSZ == 2148037735: # L is not required in Python >= 2.2.
1637 TIOCSWINSZ = -2146929561 # Same bits, but with sign.
1638 # Note, assume ws_xpixel and ws_ypixel are zero.
1639 s = struct.pack("HHHH", r, c, 0, 0)
1640 fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
1641
1642 def interact(self, escape_character=None, input_filter=None, output_filter=None):
1643 """Give control of the child process to the interactive user.
1644
1645 The interactive user is the human at the keyboard.
1646
1647 Keystrokes are sent to the child process, and the stdout and stderr
1648 output of the child process is printed. This simply echos the child
1649 stdout and child stderr to the real stdout and it echos the real stdin
1650 to the child stdin. When the user types the escape_character this
1651 method will stop. The default for escape_character is ^]. This should
1652 not be confused with ASCII 27 -- the ESC character. ASCII 29 was chosen
1653 for historical merit because this is the character used by 'telnet' as
1654 the escape character. The escape_character will not be sent to the
1655 child process.
1656
1657 You may pass in optional input and output filter functions. These
1658 functions should take a string and return a string. The output_filter
1659 will be passed all the output from the child process. The input_filter
1660 will be passed all the keyboard input from the user. The input_filter
1661 is run BEFORE the check for the escape_character.
1662
1663 Note that if you change the window size of the parent the SIGWINCH
1664 signal will not be passed through to the child. If you want the child
1665 window size to change when the parent's window size changes then do
1666 something like the following example::
1667
1668 import pexpect, struct, fcntl, termios, signal, sys
1669 def sigwinch_passthrough (sig, data):
1670 s = struct.pack("HHHH", 0, 0, 0, 0)
1671 a = struct.unpack(
1672 'hhhh',
1673 fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s)
1674 )
1675 global p
1676 p.setwinsize(a[0],a[1])
1677 # Note this is global and used in sigwinch_passthrough.
1678 p = pexpect.spawn('/bin/bash')
1679 signal.signal(signal.SIGWINCH, sigwinch_passthrough)
1680 p.interact()
1681 """
1682 if escape_character is None:
1683 escape_character = chr(29)
1684
1685 # Flush the buffer.
1686 self.stdout.write(self.buffer)
1687 self.stdout.flush()
1688 self.buffer = ""
1689 mode = tty.tcgetattr(self.STDIN_FILENO)
1690 tty.setraw(self.STDIN_FILENO)
1691 try:
1692 self.__interact_copy(escape_character, input_filter, output_filter)
1693 finally:
1694 tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
1695
1696 def __interact_writen(self, fd, data):
1697 """Write data to the file descriptor."""
1698 if not isinstance(data, bytes):
1699 data = data.encode("utf-8")
1700 while data != b"" and self.isalive():
1701 n = os.write(fd, data)
1702 data = data[n:]
1703
1704 def __interact_read(self, fd):
1705 """Read 1000 bytes from the file descriptor."""
1706 return os.read(fd, 1000)
1707
1708 def __interact_copy(
1709 self, escape_character=None, input_filter=None, output_filter=None
1710 ):
1711 """Copy data between the child and the user."""
1712 while self.isalive():
1713 r, w, e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
1714 if self.child_fd in r:
1715 try:
1716 data = self.__interact_read(self.child_fd)
1717 except OSError:
1718 break
1719 if output_filter:
1720 data = output_filter(data)
1721 if self.logfile is not None:
1722 self.logfile.write(data)
1723 self.logfile.flush()
1724 os.write(self.STDOUT_FILENO, data)
1725 if self.STDIN_FILENO in r:
1726 data = self.__interact_read(self.STDIN_FILENO)
1727 if input_filter:
1728 data = input_filter(data)
1729 i = data.rfind(escape_character)
1730 if i != -1:
1731 data = data[:i]
1732 self.__interact_writen(self.child_fd, data)
1733 break
1734 self.__interact_writen(self.child_fd, data)
1735
1736 def __select(self, iwtd, owtd, ewtd, timeout=None):
1737 """Wrap around select.select() to ignores signals.
1738
1739 If select.select raises a select.error exception and errno is an EINTR
1740 error then it is ignored. Mainly this is used to ignore sigwinch
1741 (terminal resize).
1742 """
1743 # if select() is interrupted by a signal (errno==EINTR) then
1744 # we loop back and enter the select() again.
1745 end_time = -1
1746 if timeout is not None:
1747 end_time = time.time() + timeout
1748 while True:
1749 try:
1750 return select.select(iwtd, owtd, ewtd, timeout)
1751 except OSError as e:
1752 if e[0] == errno.EINTR:
1753 # if we loop back we have to subtract
1754 # the amount of time we already waited.
1755 if timeout is not None:
1756 timeout = end_time - time.time()
1757 if timeout < 0:
1758 return ([], [], [])
1759 else:
1760 # something else caused the select.error,
1761 # so this really is an exception
1762 raise e
1763
1764 ##############################################################################
1765 # The following methods are no longer supported or allowed.
1766
1767 def setmaxread(self, maxread):
1768 """This method is no longer supported or allowed.
1769
1770 I don't like getters and setters without a good reason.
1771 """
1772 raise ExceptionPexpect(
1773 "This method is no longer supported or allowed. "
1774 "Just assign a value to the maxread member variable."
1775 )
1776
1777 def setlog(self, fileobject):
1778 """This method is no longer supported or allowed."""
1779 raise ExceptionPexpect(
1780 "This method is no longer supported or allowed. "
1781 "Just assign a value to the logfile member variable."
1782 )
1783
1784
1785 ##############################################################################
1786 # End of spawn_unix class
1787 ##############################################################################
1788
1789
1790 class SpawnWindows(SpawnUnix):
1791 """The main class interface for Pexpect.
1792
1793 Use this class to start and control child applications.
1794 """
1795
1796 def __init__(
1797 self,
1798 command,
1799 args=None,
1800 timeout=30,
1801 maxread=60000,
1802 searchwindowsize=None,
1803 logfile=None,
1804 cwd=None,
1805 env=None,
1806 codepage=None,
1807 columns=None,
1808 rows=None,
1809 ):
1810 # super(spawn_windows, self).__init__(
1811 # command=command,
1812 # args=args,
1813 # timeout=timeout,
1814 # maxread=maxread,
1815 # searchwindowsize=searchwindowsize,
1816 # logfile=logfile,
1817 # cwd=cwd,
1818 # env=env
1819 # )
1820 self.stdin = sys.stdin
1821 self.stdout = sys.stdout
1822 self.stderr = sys.stderr
1823 self.searcher = None
1824 self.ignorecase = False
1825 self.before = None
1826 self.after = None
1827 self.match = None
1828 self.match_index = None
1829 self.terminated = True
1830 self.exitstatus = None
1831 self.signalstatus = None
1832 self.status = None # status returned by os.waitpid
1833 self.flag_eof = False
1834 self.pid = None
1835 self.child_fd = -1 # initially closed
1836 self.timeout = timeout
1837 self.delimiter = EOF
1838 self.logfile = logfile
1839 self.logfile_read = None # input from child (read_nonblocking)
1840 self.logfile_send = None # output to send (send, sendline)
1841 self.maxread = maxread # max bytes to read at one time into buffer
1842 self.buffer = "" # This is the read buffer. See maxread.
1843 self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. # noqa: E501
1844 self.delaybeforesend = 0.05 # Sets sleep time used just before sending data to child. Time in seconds. # noqa: E501
1845 self.delayafterclose = 0.1 # Sets delay in close() method to allow kernel time to update process status. Time in seconds. # noqa: E501
1846 self.delayafterterminate = 0.1 # Sets delay in terminate() method to allow kernel time to update process status. Time in seconds. # noqa: E501
1847 self.softspace = False # File-like object.
1848 self.name = f"<{self!r}>" # File-like object.
1849 self.encoding = None # File-like object.
1850 self.closed = True # File-like object.
1851 self.ocwd = os.getcwd()
1852 self.cwd = cwd
1853 self.env = env
1854 self.codepage = codepage
1855 self.columns = columns
1856 self.rows = rows
1857 self.wtty = None
1858
1859 if args is None:
1860 args = []
1861
1862 # if any of the args contain any spaces (most possibly a path),
1863 # we need to quote them
1864 for i, arg in enumerate(args):
1865 if " " in arg and arg[0] != '"' and arg[-1] != '"':
1866 log(f"Quoting argument {i}: {arg}")
1867 args[i] = f'"{arg}"'
1868
1869 # allow dummy instances for subclasses that may not use command or args.
1870 if command is None:
1871 self.command = None
1872 self.args = None
1873 self.name = "<pexpect factory incomplete>"
1874 else:
1875 self._spawn(command, args)
1876
1877 def __del__(self):
1878 """Make sure that no system resources are left open.
1879
1880 Python only garbage collects Python objects, not the child console.
1881 """
1882 with contextlib.suppress(Exception):
1883 self.wtty.terminate_child()
1884 with contextlib.suppress(Exception):
1885 self.wtty.terminate()
1886
1887 def _spawn(self, command, args=None):
1888 """Start the given command in a child process.
1889
1890 This does all the fork/exec type of stuff for a pty. This is called by
1891 __init__. If args is empty then command will be parsed (split on
1892 spaces) and args will be set to parsed arguments.
1893 """
1894 if args is None:
1895 args = []
1896
1897 # The pid and child_fd of this object get set by this method.
1898 # Note that it is difficult for this method to fail.
1899 # You cannot detect if the child process cannot start.
1900 # So the only way you can tell if the child process started
1901 # or not is to try to read from the file descriptor. If you get
1902 # EOF immediately then it means that the child is already dead.
1903 # That may not necessarily be bad because you may haved spawned a child
1904 # that performs some task; creates no stdout output; and then dies.
1905
1906 # If command is an int type then it may represent a file descriptor.
1907 if isinstance(command, int):
1908 raise ExceptionPexpect(
1909 "Command is an int type. If this is a file descriptor then"
1910 "maybe you want to use fdpexpect.fdspawn which takes an "
1911 "existing file descriptor instead of a command string."
1912 )
1913
1914 if not isinstance(args, list):
1915 raise TypeError("The argument, args, must be a list.")
1916
1917 if not args:
1918 # Momentairly broken - path '\' characters being misinterpreted
1919 # self.args = split_command_line(command)
1920 self.args = [command]
1921 self.command = self.args[0]
1922 else:
1923 self.args = args[:] # work with a copy
1924 self.args.insert(0, command)
1925 self.command = command
1926
1927 command_with_path = which(self.command)
1928 if command_with_path is None:
1929 raise ExceptionPexpect(
1930 f"The command was not found or was not executable: {self.command}."
1931 )
1932 self.command = command_with_path
1933 self.args[0] = self.command
1934
1935 self.name = f"<{' '.join(self.args)}>"
1936
1937 # assert self.pid is None, 'The pid member should be None.'
1938 # assert self.command is not None, 'The command member should not be None.'
1939
1940 self.wtty = Wtty(
1941 timeout=self.timeout,
1942 codepage=self.codepage,
1943 columns=self.columns,
1944 rows=self.rows,
1945 cwd=self.cwd,
1946 )
1947
1948 self.child_fd = self.wtty.spawn(self.command, self.args, self.env)
1949
1950 self.terminated = False
1951 self.closed = False
1952 self.pid = self.wtty.pid
1953
1954 def fileno(self): # File-like object.
1955 """There is no child fd."""
1956 return 0
1957
1958 def close(self, force=True): # File-like object.
1959 """Close the child console."""
1960 self.closed = self.terminate(force)
1961 if not self.closed:
1962 raise ExceptionPexpect(
1963 "close() could not terminate the child using terminate()"
1964 )
1965 self.closed = True
1966
1967 def isatty(self): # File-like object.
1968 """The child is always created with a console."""
1969 return True
1970
1971 def getecho(self):
1972 """Return the terminal echo mode.
1973
1974 This returns True if echo is on or False if echo is off. Child
1975 applications that are expecting you to enter a password often set ECHO
1976 False. See waitnoecho().
1977 """
1978 return self.wtty.getecho()
1979
1980 def setecho(self, state):
1981 """Set the terminal echo mode on or off."""
1982 self.wtty.setecho(state)
1983
1984 def read_nonblocking(self, size=1, timeout=-1):
1985 """Read at most size characters from the child application.
1986
1987 It includes a timeout. If the read does not complete within the timeout
1988 period then a TIMEOUT exception is raised. If the end of file is read
1989 then an EOF exception will be raised. If a log file was set using
1990 setlog() then all data will also be written to the log file.
1991
1992 If timeout is None then the read may block indefinitely. If timeout is
1993 -1 then the self.timeout value is used. If timeout is 0 then the child
1994 is polled and if there was no data immediately ready then this will
1995 raise a TIMEOUT exception.
1996
1997 The timeout refers only to the amount of time to read at least one
1998 character. This is not effected by the 'size' parameter, so if you call
1999 read_nonblocking(size=100, timeout=30) and only one character is
2000 available right away then one character will be returned immediately.
2001 It will not wait for 30 seconds for another 99 characters to come in.
2002
2003 This is a wrapper around Wtty.read().
2004 """
2005 if self.closed:
2006 raise ValueError("I/O operation on closed file in read_nonblocking().")
2007
2008 if timeout == -1:
2009 timeout = self.timeout
2010
2011 s = self.wtty.read_nonblocking(timeout, size)
2012 if s == "":
2013 if not self.wtty.isalive():
2014 self.flag_eof = True
2015 raise EOF("End Of File (EOF) in read_nonblocking().")
2016 if timeout is None:
2017 # Do not raise TIMEOUT because we might be waiting for EOF
2018 # sleep to keep CPU utilization down
2019 time.sleep(0.05)
2020 else:
2021 raise TIMEOUT("Timeout exceeded in read_nonblocking().")
2022 else:
2023 if self.logfile is not None:
2024 self.logfile.write(s)
2025 self.logfile.flush()
2026 if self.logfile_read is not None:
2027 self.logfile_read.write(s)
2028 self.logfile_read.flush()
2029
2030 return s
2031
2032 def send(self, s):
2033 """Send a string to the child process.
2034
2035 This returns the number of bytes written. If a log file was set then
2036 the data is also written to the log.
2037 """
2038 time.sleep(self.delaybeforesend)
2039 if self.logfile is not None:
2040 self.logfile.write(s)
2041 self.logfile.flush()
2042 if self.logfile_send is not None:
2043 self.logfile_send.write(s)
2044 self.logfile_send.flush()
2045 return self.wtty.write(s)
2046
2047 # UNIMPLEMENTED ###
2048 def sendcontrol(self, char):
2049 raise ExceptionPexpect("sendcontrol() is not supported on windows")
2050
2051 # UNIMPLEMENTED ###
2052 # Parent buffer does not wait for endline by default.
2053 def sendeof(self):
2054 raise ExceptionPexpect("sendeof() is not supported on windows")
2055
2056 def sendintr(self):
2057 """Send a SIGINT to the child.
2058
2059 It does not require the SIGINT to be the first character on a line.
2060 """
2061 self.wtty.sendintr()
2062
2063 def terminate(self, force=False):
2064 """Terminate the child. Force not used."""
2065 if not self.isalive():
2066 return True
2067
2068 self.wtty.terminate_child()
2069 time.sleep(self.delayafterterminate)
2070 return not self.isalive()
2071
2072 def kill(self, sig):
2073 """Sig == sigint for ctrl-c otherwise the child is terminated."""
2074 if sig == signal.SIGINT:
2075 self.wtty.sendintr()
2076 else:
2077 self.wtty.terminate_child()
2078
2079 def wait(self):
2080 """Wait until the child exits.
2081
2082 This is a blocking call. This will not read any data from the child, so
2083 this will block forever if the child has unread output and has
2084 terminated. In other words, the child may have printed output then
2085 called exit(); but, technically, the child is still alive until its
2086 output is read.
2087 """
2088 if not self.isalive():
2089 raise ExceptionPexpect("Cannot wait for dead child process.")
2090
2091 # We can't use os.waitpid under Windows because of 'permission denied'
2092 # exception? Perhaps if not running as admin (or UAC enabled under
2093 # Vista/7). Simply loop and wait for child to exit.
2094 while self.isalive():
2095 time.sleep(0.05) # Keep CPU utilization down
2096
2097 return self.exitstatus
2098
2099 def isalive(self):
2100 """Determine if the child is still alive."""
2101 if self.terminated:
2102 return False
2103
2104 if self.wtty.isalive():
2105 return True
2106 self.exitstatus = GetExitCodeProcess(self.wtty.getchild())
2107 # left-shift exit status by 8 bits like os.waitpid
2108 self.status = self.exitstatus << 8
2109 self.terminated = True
2110 return False
2111
2112 def getwinsize(self):
2113 """Return the terminal window size of the child tty.
2114
2115 The return value is a tuple of (rows, cols).
2116 """
2117 return self.wtty.getwinsize()
2118
2119 def setwinsize(self, r, c):
2120 """Set the size of the child screen buffer."""
2121 self.wtty.setwinsize(r, c)
2122
2123 # Prototype changed
2124 def interact(self, escape_character=None, input_filter=None, output_filter=None):
2125 """Make the child console visible for interaction."""
2126 if escape_character is None:
2127 escape_character = chr(29)
2128 self.wtty.interact()
2129
2130 # Prototype changed
2131 def stop_interact(self):
2132 """Hide the child console from the user."""
2133 self.wtty.stop_interact()
2134
2135
2136 class Wtty:
2137 """This class is used to spawn a child process and connect to its console.
2138
2139 It is used by the spawn_windows class. This class is not intended to be
2140 used directly.
2141 """
2142
2143 def __init__(self, timeout=30, codepage=None, columns=None, rows=None, cwd=None):
2144 self.__buffer = StringIO()
2145 self.__bufferY = 0
2146 self.__currentReadCo = PyCOORDType(0, 0)
2147 self.__parentPid = 0
2148 self.__oproc = 0
2149 self.conpid = 0
2150 self.__otid = 0
2151 self.__switch = True
2152 self.__childProcess = None
2153 self.codepage = (
2154 codepage
2155 or windll.kernel32.GetConsoleOutputCP()
2156 or windll.kernel32.GetOEMCP()
2157 )
2158 log(f"Code page: {self.codepage}")
2159 log(f"hasattr(sys, 'frozen'): {hasattr(sys, 'frozen')}")
2160 if getattr(sys, "frozen", False):
2161 log(f"sys.frozen : {sys.frozen}")
2162 log(f"type(sys.frozen) : {type(sys.frozen)}")
2163 self.columns = columns
2164 if isinstance(cwd, bytes):
2165 cwd = cwd.decode("utf-8")
2166 self.cwd = cwd
2167 self.rows = rows
2168 self.console = False
2169 self.lastRead = 0
2170 self.lastReadData = ""
2171 self.pid = None
2172 self.processList = []
2173 # We need a timeout for connecting to the child process
2174 self.timeout = timeout
2175 self.totalRead = 0
2176
2177 def spawn(self, command, args=None, env=None):
2178 """Spawn spawner.py with correct arguments."""
2179 if args is None:
2180 args = []
2181
2182 ts = time.time()
2183 self.startChild(args, env)
2184
2185 while True:
2186 msg = PeekMessage(0, 0, 0, PM_REMOVE)
2187 childPid = msg[1][2]
2188 # Sometimes GetMessage returns a bogus PID, so keep calling it
2189 # until we can successfully connect to the child or timeout is
2190 # reached
2191 if childPid:
2192 try:
2193 self.__childProcess = win32api.OpenProcess(
2194 PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, False, childPid
2195 )
2196 except pywintypes.error:
2197 pass
2198 else:
2199 self.pid = childPid
2200 break
2201 if time.time() > ts + self.timeout:
2202 log("Timeout exceeded in Wtty.spawn().")
2203 break
2204 time.sleep(0.05)
2205
2206 if not self.__childProcess:
2207 raise ExceptionPexpect(f"The process {args[0]} could not be started.")
2208
2209 winHandle = int(GetConsoleWindow())
2210 self.__switch = True
2211 if winHandle != 0:
2212 self.__parentPid = GetWindowThreadProcessId(winHandle)[1]
2213 # Do we have a console attached? Do not rely on winHandle, because
2214 # it will also be non-zero if we didn't have a console, and then
2215 # spawned a child process! Using sys.stdout.isatty() seems safe
2216 self.console = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
2217 # If the original process had a console, record a list of attached
2218 # processes so we can check if we need to reattach/reallocate the
2219 # console later
2220 self.processList = GetConsoleProcessList()
2221 else:
2222 self.switchTo(False)
2223 self.__switch = False
2224
2225 def startChild(self, args, env):
2226 si = GetStartupInfo()
2227 si.dwFlags = STARTF_USESHOWWINDOW
2228 si.wShowWindow = SW_HIDE
2229 # Determine the directory of wexpect.py or, if we are running 'frozen'
2230 # (eg. py2exe deployment), of the packed executable
2231 dirname = os.path.dirname(
2232 sys.executable
2233 if getattr(sys, "frozen", False)
2234 else os.path.abspath(os.path.dirname(__file__))
2235 )
2236 logdir = APPNAME if getattr(sys, "frozen", False) else dirname
2237 logdir = os.path.basename(logdir)
2238 spath = [dirname]
2239 pyargs = ["-c"]
2240 if getattr(sys, "frozen", False):
2241 # If we are running 'frozen', add library.zip and lib\library.zip
2242 # to sys.path
2243 # py2exe: Needs appropriate 'zipfile' option in setup script and
2244 # 'bundle_files' 3
2245 spath.append(os.path.join(dirname, "library.zip"))
2246 spath.append(os.path.join(dirname, "library.zip", APPNAME))
2247 if os.path.isdir(os.path.join(dirname, "lib")):
2248 dirname = os.path.join(dirname, "lib")
2249 spath.append(os.path.join(dirname, "library.zip"))
2250 spath.append(os.path.join(dirname, "library.zip", APPNAME))
2251 spath.append(os.path.join(dirname, "temp"))
2252
2253 pyargs.insert(0, "-S") # skip 'import site'
2254 pid = GetCurrentProcessId()
2255 tid = win32api.GetCurrentThreadId()
2256 # If we are running 'frozen', expect python.exe in the same directory
2257 # as the packed executable.
2258 # py2exe: The python executable can be included via setup script by
2259 # adding it to 'data_files'
2260 command_line = '"{}" {} "{}"'.format(
2261 (
2262 os.path.join(dirname, "python.exe")
2263 if getattr(sys, "frozen", False)
2264 else os.path.join(os.path.dirname(sys.executable), "python.exe")
2265 ),
2266 " ".join(pyargs),
2267 "import sys;{}sys.path = {} + sys.path;"
2268 "args = {}; from DisplayCAL import wexpect;"
2269 "wexpect.ConsoleReader("
2270 "wexpect.join_args(args), {:d}, {:d}, cp={}, c={}, r={}, logdir={!r}"
2271 ")".format(
2272 # this fixes running Argyll commands through py2exe frozen python
2273 (
2274 f"setattr(sys, 'frozen', '{sys.frozen}'); "
2275 if hasattr(sys, "frozen")
2276 else ""
2277 ),
2278 (f"{spath!r}").replace('"', r"\""),
2279 (f"{args!r}").replace('"', r"\""),
2280 pid,
2281 tid,
2282 self.codepage,
2283 self.columns,
2284 self.rows,
2285 logdir,
2286 ),
2287 )
2288
2289 log(f"command_line: {command_line}")
2290
2291 if getattr(sys, "frozen", False):
2292 # without the PYTHONHOME and PYTHONPATH the executable will not run
2293 # with the frozen python interpreter
2294 env["PYTHONHOME"] = dirname
2295 env["PYTHONPATH"] = os.pathsep.join(spath)
2296
2297 log(f"env: {env}")
2298
2299 self.__oproc, _, self.conpid, self.__otid = CreateProcess(
2300 None, command_line, None, None, False, CREATE_NEW_CONSOLE, env, self.cwd, si
2301 )
2302
2303 def switchTo(self, attached=True):
2304 """Release from the current console and attatches to the childs."""
2305 if not self.__switch or not self.__oproc_isalive():
2306 return
2307
2308 if attached:
2309 FreeConsole()
2310
2311 AttachConsole(self.conpid)
2312 self.__consin = GetStdHandle(STD_INPUT_HANDLE)
2313 self.__consout = self.getConsoleOut()
2314
2315 def switchBack(self):
2316 """Release from the current console and attaches to the parents."""
2317 if not self.__switch or not self.__oproc_isalive():
2318 return
2319
2320 if self.console:
2321 # If we originally had a console, re-attach it (or allocate a new one)
2322 # If we didn't have a console to begin with, there's no need to
2323 # re-attach/allocate
2324 FreeConsole()
2325 if len(self.processList) > 1:
2326 # Our original console is still present, re-attach
2327 AttachConsole(self.__parentPid)
2328 else:
2329 # Our original console has been free'd, allocate a new one
2330 AllocConsole()
2331
2332 self.__consin = None
2333 self.__consout = None
2334
2335 def getConsoleOut(self):
2336 consout = win32file.CreateFile(
2337 "CONOUT$",
2338 GENERIC_READ | GENERIC_WRITE,
2339 FILE_SHARE_READ | FILE_SHARE_WRITE,
2340 None,
2341 OPEN_EXISTING,
2342 0,
2343 0,
2344 )
2345 return PyConsoleScreenBufferType(consout)
2346
2347 def getchild(self):
2348 """Return a handle to the child process."""
2349 return self.__childProcess
2350
2351 def terminate(self):
2352 """Terminate the ConsoleReader process."""
2353 win32api.TerminateProcess(self.__oproc, 1)
2354
2355 def terminate_child(self):
2356 """Terminate the child process."""
2357 win32api.TerminateProcess(self.__childProcess, 1)
2358
2359 def createKeyEvent(self, char):
2360 """Create a single key record corresponding to the ascii character char."""
2361 evt = PyINPUT_RECORDType(KEY_EVENT)
2362 evt.KeyDown = True
2363 evt.Char = char
2364 if char in ("\n", "\r"):
2365 evt.VirtualKeyCode = 0x0D # VK_RETURN
2366 evt.RepeatCount = 1
2367 return evt
2368
2369 def write(self, s):
2370 """Write input into the child consoles input buffer."""
2371 if len(s) == 0:
2372 return 0
2373 records = [self.createKeyEvent(c) for c in str(s)]
2374 self.switchTo()
2375 try:
2376 wrote = self.__consin.WriteConsoleInput(records)
2377 except Exception as e:
2378 log(e, "_exceptions")
2379 self.switchBack()
2380 raise
2381 self.switchBack()
2382 return wrote
2383
2384 def getPoint(self, offset):
2385 """Convert an offset to a point represented as a tuple."""
2386 consinfo = self.__consout.GetConsoleScreenBufferInfo()
2387 x = offset % consinfo["Size"].X
2388 y = offset / consinfo["Size"].X
2389 return x, y
2390
2391 def getOffset(self, x, y):
2392 """Convert a tuple-point to an offset."""
2393 consinfo = self.__consout.GetConsoleScreenBufferInfo()
2394 return x + y * consinfo["Size"].X
2395
2396 def readConsole(self, startCo, endCo):
2397 """Read the console area from startCo to endCo and return it as a string."""
2398 buff = []
2399 self.lastRead = 0
2400
2401 startCo = PyCOORDType(startCo.X, startCo.Y)
2402 endX = endCo.X
2403 endY = endCo.Y
2404
2405 while True:
2406 startOff = self.getOffset(startCo.X, startCo.Y)
2407 endOff = self.getOffset(endX, endY)
2408 readlen = endOff - startOff
2409
2410 if readlen > 4000:
2411 readlen = 4000
2412 endPoint = self.getPoint(startOff + 4000)
2413 else:
2414 endPoint = self.getPoint(endOff)
2415
2416 s = self.__consout.ReadConsoleOutputCharacter(readlen, startCo)
2417 ln = len(s)
2418 self.lastRead += ln
2419 self.totalRead += ln
2420 buff.append(s)
2421
2422 startCo.X, startCo.Y = int(endPoint[0]), int(endPoint[1])
2423 if readlen <= 0 or (startCo.X >= endX and startCo.Y >= endY): # noqa: SIM300
2424 break
2425
2426 return "".join(buff)
2427
2428 def parseData(self, s):
2429 """Ensure that special characters are interpreted as newlines or blanks.
2430
2431 Depending on if there written over characters or screen-buffer-fill characters.
2432 """
2433 consinfo = self.__consout.GetConsoleScreenBufferInfo()
2434 strlist = []
2435 for i, c in enumerate(s):
2436 strlist.append(c)
2437 if (self.totalRead - self.lastRead + i + 1) % consinfo["Size"].X == 0:
2438 strlist.append("\r\n")
2439
2440 s = "\r\n".join([line.rstrip(" ") for line in "".join(strlist).split("\r\n")])
2441 try:
2442 return s # .encode("cp%i" % self.codepage, "replace")
2443 except LookupError:
2444 return s # .encode(
2445 # getattr(sys.stdout, "encoding", None) or sys.getdefaultencoding(),
2446 # "replace",
2447 # )
2448
2449 def readConsoleToCursor(self):
2450 """Read from current position to cursor and update self.__buffer."""
2451 if not self.__consout:
2452 return ""
2453
2454 consinfo = self.__consout.GetConsoleScreenBufferInfo()
2455 cursorPos = consinfo["CursorPosition"]
2456
2457 # log('=' * 80)
2458 # log('cursor: %r, current: %r' % (cursorPos, self.__currentReadCo))
2459
2460 if cursorPos.Y < self.__currentReadCo.Y:
2461 # Has the child cleared the screen buffer?
2462 self.__buffer.seek(0)
2463 self.__buffer.truncate()
2464 self.__bufferY = 0
2465 self.__currentReadCo.X = 0
2466 self.__currentReadCo.Y = 0
2467
2468 isSameX = cursorPos.X == self.__currentReadCo.X
2469 isSameY = cursorPos.Y == self.__currentReadCo.Y
2470 isSamePos = isSameX and isSameY
2471
2472 # log('isSameY: %r' % isSameY)
2473 # log('isSamePos: %r' % isSamePos)
2474
2475 if isSameY or not self.lastReadData.endswith("\r\n"):
2476 # Read the current slice again
2477 self.totalRead -= self.lastRead
2478 self.__currentReadCo.X = 0
2479 self.__currentReadCo.Y = self.__bufferY
2480
2481 # log('cursor: %r, current: %r' % (cursorPos, self.__currentReadCo))
2482
2483 raw = self.readConsole(self.__currentReadCo, cursorPos)
2484 rawlist = []
2485 while raw:
2486 rawlist.append(raw[: consinfo["Size"].X])
2487 raw = raw[consinfo["Size"].X :]
2488 raw = "".join(rawlist)
2489 s = self.parseData(raw)
2490 for i, line in enumerate(reversed(rawlist)):
2491 if len(line) == consinfo["Size"].X:
2492 # Record the Y offset where the most recent line break was detected
2493 self.__bufferY += len(rawlist) - i
2494 break
2495
2496 # log('lastReadData: %r' % self.lastReadData)
2497 # log('s: %r' % s)
2498
2499 # isSameData = False
2500 if isSamePos and self.lastReadData == s:
2501 # isSameData = True
2502 s = ""
2503
2504 # log('isSameData: %r' % isSameData)
2505 # log('s: %r' % s)
2506 if s:
2507 lastReadData = self.lastReadData
2508 pos = self.getOffset(self.__currentReadCo.X, self.__currentReadCo.Y)
2509 self.lastReadData = s
2510 if isSameY or not lastReadData.endswith("\r\n"):
2511 # Detect changed lines
2512 self.__buffer.seek(pos)
2513 buf = self.__buffer.read()
2514 # log('buf: %r' % buf)
2515 # log('raw: %r' % raw)
2516 if raw.startswith(buf):
2517 # Line has grown
2518 rawslice = raw[len(buf) :]
2519 # Update last read bytes so line breaks can be detected in parseData
2520 lastRead = self.lastRead
2521 self.lastRead = len(rawslice)
2522 s = self.parseData(rawslice)
2523 self.lastRead = lastRead
2524 else:
2525 # Cursor has been repositioned
2526 s = "\r" + s
2527 # log('s: %r' % s)
2528 self.__buffer.seek(pos)
2529 self.__buffer.truncate()
2530 self.__buffer.write(raw)
2531
2532 self.__currentReadCo.X = cursorPos.X
2533 self.__currentReadCo.Y = cursorPos.Y
2534
2535 return s
2536
2537 def read_nonblocking(self, timeout, size):
2538 """Read data from the console if available, else wait up to timeout seconds."""
2539 self.switchTo()
2540
2541 consinfo = self.__consout.GetConsoleScreenBufferInfo()
2542 cursorPos = consinfo["CursorPosition"]
2543 maxconsoleY = consinfo["Size"].Y / 2
2544 reset = False
2545 eof = False
2546 try:
2547 while True:
2548 # Wait for child process to be paused
2549 if cursorPos.Y > maxconsoleY: # noqa: SIM300
2550 reset = True
2551 time.sleep(0.2)
2552
2553 start = time.time()
2554 s = self.readConsoleToCursor()
2555
2556 if reset:
2557 self.refreshConsole()
2558 reset = False
2559
2560 if len(s) != 0:
2561 self.switchBack()
2562 return s
2563
2564 if eof or timeout <= 0:
2565 self.switchBack()
2566 if eof and self.__oproc_isalive():
2567 try:
2568 TerminateProcess(self.__oproc, 0)
2569 except pywintypes.error as e:
2570 log(e, "_exceptions")
2571 log("Could not terminate ConsoleReader after child exited.")
2572 return ""
2573
2574 if not self.isalive():
2575 eof = True
2576 # Child has already terminated, but there may still be
2577 # output coming in with a slight delay
2578 time.sleep(0.1)
2579
2580 time.sleep(0.001)
2581 end = time.time()
2582 timeout -= end - start
2583
2584 except Exception as e:
2585 log(e, "_exceptions")
2586 log("End Of File (EOF) in Wtty.read_nonblocking().")
2587 self.switchBack()
2588 raise EOF("End Of File (EOF) in Wtty.read_nonblocking().") from e
2589
2590 def refreshConsole(self):
2591 """Pause the child, read all current console data and clear the console.
2592
2593 The last line before clearing becomes the first after clearing.
2594 """
2595 consinfo = self.__consout.GetConsoleScreenBufferInfo()
2596 cursorPos = consinfo["CursorPosition"]
2597 startCo = PyCOORDType(0, cursorPos.Y)
2598 self.totalRead = 0
2599 raw = self.readConsole(startCo, cursorPos)
2600 orig = PyCOORDType(0, 0)
2601 self.__consout.SetConsoleCursorPosition(orig)
2602 writelen = consinfo["Size"].X * consinfo["Size"].Y
2603 self.__consout.FillConsoleOutputCharacter(" ", writelen, orig)
2604 self.__consout.WriteConsoleOutputCharacter(raw, orig)
2605 cursorPos.Y = 0
2606 self.__consout.SetConsoleCursorPosition(cursorPos)
2607 self.__currentReadCo = cursorPos
2608
2609 self.__bufferY = 0
2610 self.__buffer.truncate(0)
2611 self.__buffer.write(raw)
2612
2613 def setecho(self, state):
2614 """Set the echo mode of the child console."""
2615 self.switchTo()
2616 try:
2617 mode = self.__consin.GetConsoleMode()
2618 if state:
2619 mode |= 0x0004
2620 else:
2621 mode &= ~0x0004
2622 self.__consin.SetConsoleMode(mode)
2623 except BaseException:
2624 self.switchBack()
2625 raise
2626 self.switchBack()
2627
2628 def getecho(self):
2629 """Return the echo mode of the child console."""
2630 self.switchTo()
2631 try:
2632 mode = self.__consin.GetConsoleMode()
2633 ret = (mode & 0x0004) > 0
2634 self.switchBack()
2635 except BaseException:
2636 self.switchBack()
2637 raise
2638 return ret
2639
2640 def getwinsize(self):
2641 """Return the size of the child console as a tuple of (rows, columns)."""
2642 self.switchTo()
2643 try:
2644 size = self.__consout.GetConsoleScreenBufferInfo()["Size"]
2645 self.switchBack()
2646 except BaseException:
2647 self.switchBack()
2648 raise
2649 return (size.Y, size.X)
2650
2651 def setwinsize(self, r, c):
2652 """Set the child console screen buffer size to (r, c)."""
2653 self.switchTo()
2654 try:
2655 self.__consout.SetConsoleScreenBufferSize(PyCOORDType(c, r))
2656 except Exception:
2657 self.switchBack()
2658 raise
2659 self.switchBack()
2660
2661 def interact(self):
2662 """Display the child console for interaction."""
2663 if not self.isalive():
2664 return
2665
2666 self.switchTo()
2667 try:
2668 ShowWindow(GetConsoleWindow(), SW_SHOW)
2669 except Exception:
2670 self.switchBack()
2671 raise
2672 self.switchBack()
2673
2674 def stop_interact(self):
2675 """Hide the child console."""
2676 self.switchTo()
2677 try:
2678 ShowWindow(GetConsoleWindow(), SW_HIDE)
2679 except Exception:
2680 self.switchBack()
2681 raise
2682 self.switchBack()
2683
2684 def isalive(self):
2685 """True if the child is still alive, false otherwise."""
2686 return GetExitCodeProcess(self.__childProcess) == STILL_ACTIVE
2687
2688 def __oproc_isalive(self):
2689 return GetExitCodeProcess(self.__oproc) == STILL_ACTIVE
2690
2691 def sendintr(self):
2692 """Send the sigint signal to the child."""
2693 self.switchTo()
2694 try:
2695 time.sleep(0.15)
2696 win32api.GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, self.pid)
2697 time.sleep(0.25)
2698 except Exception:
2699 self.switchBack()
2700 raise
2701 self.switchBack()
2702
2703
2704 class ConsoleReader:
2705 def __init__(self, path, pid, tid, env=None, cp=None, c=None, r=None, logdir=None):
2706 self.logdir = logdir
2707 log("=" * 80, "consolereader", logdir)
2708 log(f"OEM code page: {windll.kernel32.GetOEMCP()}", "consolereader", logdir)
2709 consolecp = windll.kernel32.GetConsoleOutputCP()
2710 log(f"Console output code page: {consolecp}", "consolereader", logdir)
2711 if consolecp != cp:
2712 log(f"Setting console output code page to {cp}", "consolereader", logdir)
2713 try:
2714 SetConsoleOutputCP(cp)
2715 except Exception as e:
2716 log(e, "consolereader_exceptions", logdir)
2717 else:
2718 log(
2719 f"Console output code page: {windll.kernel32.GetConsoleOutputCP()}",
2720 "consolereader",
2721 logdir,
2722 )
2723 log(f"Spawning {path}", "consolereader", logdir)
2724 try:
2725 try:
2726 consout = self.getConsoleOut()
2727 self.initConsole(consout, c, r)
2728 SetConsoleTitle(path)
2729
2730 si = GetStartupInfo()
2731 # We do not actually need stdio inherited - Wtty reads from the console.
2732 # Python 3.x sets STARTF_USESTDHANDLES flag but the stdio handles do not
2733 # correspond to console.
2734 # That causes Argyll to not write anything to console for us.
2735 si.dwFlags = STARTF_USESHOWWINDOW
2736 si.wShowWindow = SW_HIDE
2737 # si.wShowWindow = SW_SHOW
2738 self.__childProcess, _, childPid, self.__tid = CreateProcess(
2739 None,
2740 path,
2741 None,
2742 None,
2743 False,
2744 # The console has been created in the script that launches this
2745 # class, and reconfigured from here.
2746 CREATE_NEW_PROCESS_GROUP,
2747 None,
2748 None,
2749 si,
2750 )
2751 except Exception as e:
2752 log(e, "consolereader_exceptions", logdir)
2753 time.sleep(0.1)
2754 win32api.PostThreadMessage(int(tid), WM_USER, 0, 0)
2755 sys.exit()
2756
2757 time.sleep(0.1)
2758
2759 win32api.PostThreadMessage(int(tid), WM_USER, childPid, 0)
2760
2761 parent = win32api.OpenProcess(
2762 PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, 0, int(pid)
2763 )
2764 paused = False
2765
2766 cursorinfo = consout.GetConsoleCursorInfo()
2767
2768 while GetExitCodeProcess(self.__childProcess) == STILL_ACTIVE:
2769 # Only let child react to CTRL+C, ignore in ConsoleReader
2770 with contextlib.suppress(KeyboardInterrupt):
2771 if GetExitCodeProcess(parent) != STILL_ACTIVE:
2772 try:
2773 TerminateProcess(self.__childProcess, 0)
2774 except pywintypes.error as e:
2775 log(e, "consolereader_exceptions", logdir)
2776 sys.exit()
2777
2778 consinfo = consout.GetConsoleScreenBufferInfo()
2779 cursorPos = consinfo["CursorPosition"]
2780 maxconsoleY = consinfo["Size"].Y / 2
2781
2782 if cursorPos.Y > maxconsoleY and not paused: # noqa: SIM300
2783 # log(
2784 # f"ConsoleReader.__init__: cursorPos {cursorPos}",
2785 # "consolereader",
2786 # logdir
2787 # )
2788 # log("suspendThread", "consolereader", logdir)
2789 self.suspendThread()
2790 paused = True
2791 SetConsoleTitle(f"{path} (suspended)")
2792 # Hide cursor
2793 consout.SetConsoleCursorInfo(cursorinfo[0], 0)
2794
2795 if cursorPos.Y <= maxconsoleY and paused: # noqa: SIM300
2796 # log(
2797 # f"ConsoleReader.__init__: cursorPos {cursorPos}",
2798 # "consolereader",
2799 # logdir
2800 # )
2801 # log("resumeThread", "consolereader", logdir)
2802 self.resumeThread()
2803 paused = False
2804 SetConsoleTitle(path)
2805 # Show cursor
2806 consout.SetConsoleCursorInfo(cursorinfo[0], cursorinfo[1])
2807
2808 time.sleep(0.1)
2809
2810 SetConsoleTitle(f"ConsoleReader: {path} (terminated)")
2811 consout.SetConsoleCursorInfo(cursorinfo[0], 0) # Hide cursor
2812
2813 while GetExitCodeProcess(parent) == STILL_ACTIVE:
2814 time.sleep(0.1)
2815 except Exception as e:
2816 log(e, "consolereader_exceptions", logdir)
2817
2818 def handler(self, sig, logdir):
2819 log(sig, "consolereader", logdir)
2820 return False
2821
2822 def getConsoleOut(self):
2823 consout = win32file.CreateFile(
2824 "CONOUT$",
2825 GENERIC_READ | GENERIC_WRITE,
2826 FILE_SHARE_READ | FILE_SHARE_WRITE,
2827 None,
2828 OPEN_EXISTING,
2829 0,
2830 0,
2831 )
2832
2833 return PyConsoleScreenBufferType(consout)
2834
2835 def initConsole(self, consout, c=None, r=None):
2836 # Window size can't be larger than maximum window size
2837 consinfo = consout.GetConsoleScreenBufferInfo()
2838 maxwinsize = consinfo["MaximumWindowSize"]
2839 rect = PySMALL_RECTType(
2840 0, 0, min(maxwinsize.X - 1, 79), min(maxwinsize.Y - 1, 24)
2841 )
2842 consout.SetConsoleWindowInfo(True, rect)
2843 # Buffer size can't be smaller than window size
2844 size = PyCOORDType(
2845 max(rect.Right + 1, c or 80), max(rect.Bottom + 1, r or 16000)
2846 )
2847 consout.SetConsoleScreenBufferSize(size)
2848 pos = PyCOORDType(0, 0)
2849 consout.FillConsoleOutputCharacter(" ", size.X * size.Y, pos)
2850
2851 def suspendThread(self):
2852 """Pause the main thread of the child process."""
2853 handle = windll.kernel32.OpenThread(THREAD_SUSPEND_RESUME, 0, self.__tid)
2854 SuspendThread(handle)
2855
2856 def resumeThread(self):
2857 """Un-pauses the main thread of the child process."""
2858 handle = windll.kernel32.OpenThread(THREAD_SUSPEND_RESUME, 0, self.__tid)
2859 ResumeThread(handle)
2860
2861
2862 class SearcherString:
2863 """This is a plain string search helper for the spawn.expect_any() method.
2864
2865 Attributes:
2866
2867 eof_index - index of EOF, or -1
2868 timeout_index - index of TIMEOUT, or -1
2869
2870 After a successful match by the search() method the following attributes
2871 are available:
2872
2873 start - index into the buffer, first byte of match
2874 end - index into the buffer, first byte after match
2875 match - the matching string itself
2876
2877 Args:
2878 strings: A list; a sequence of strings; or the EOF or TIMEOUT types.
2879 """
2880
2881 def __init__(self, strings):
2882 self.eof_index = -1
2883 self.timeout_index = -1
2884 self._strings = []
2885 for n, s in zip(list(range(len(strings))), strings):
2886 if s is EOF:
2887 self.eof_index = n
2888 continue
2889 if s is TIMEOUT:
2890 self.timeout_index = n
2891 continue
2892 self._strings.append((n, s))
2893
2894 def __str__(self):
2895 """Return a human-readable string that represents the state of the object."""
2896 ss = [(ns[0], f' {ns[0]}: "{ns[1]}"') for ns in self._strings]
2897 ss.append((-1, "SearcherString:"))
2898 if self.eof_index >= 0:
2899 ss.append((self.eof_index, f" {self.eof_index}: EOF"))
2900 if self.timeout_index >= 0:
2901 ss.append((self.timeout_index, f" {self.timeout_index}: TIMEOUT"))
2902 ss.sort()
2903 ss = list(zip(*ss))[1]
2904 return "\n".join(ss)
2905
2906 def search(self, buffer, freshlen, searchwindowsize=None):
2907 """Searche 'buffer' for the first occurence of one of the search strings.
2908
2909 'freshlen' must indicate the number of bytes at the end of
2910 'buffer' which have not been searched before. It helps to avoid
2911 searching the same, possibly big, buffer over and over again.
2912
2913 See class spawn for the 'searchwindowsize' argument.
2914
2915 If there is a match this returns the index of that string, and sets
2916 'start', 'end' and 'match'. Otherwise, this returns -1."""
2917 absurd_match = len(buffer)
2918 first_match = absurd_match
2919
2920 # 'freshlen' helps a lot here. Further optimizations could
2921 # possibly include:
2922 #
2923 # using something like the Boyer-Moore Fast String Searching
2924 # Algorithm; pre-compiling the search through a list of
2925 # strings into something that can scan the input once to
2926 # search for all N strings; realize that if we search for
2927 # ['bar', 'baz'] and the input is '...foo' we need not bother
2928 # rescanning until we've read three more bytes.
2929 #
2930 # Sadly, I don't know enough about this interesting topic. /grahn
2931
2932 best_index = None
2933 best_match = None
2934 for index, s in self._strings:
2935 if searchwindowsize is None:
2936 # the match, if any, can only be in the fresh data,
2937 # or at the very end of the old data
2938 offset = -(freshlen + len(s))
2939 else:
2940 # better obey searchwindowsize
2941 offset = -searchwindowsize
2942 n = buffer.find(s, offset)
2943 if 0 <= n < first_match:
2944 first_match = n
2945 best_index, best_match = index, s
2946 if first_match == absurd_match:
2947 return -1
2948 self.match = best_match
2949 self.start = first_match
2950 self.end = self.start + len(self.match)
2951 return best_index
2952
2953
2954 class SearcherRegex:
2955 """Regular expression string search helper for the spawn.expect_any() method.
2956
2957 Attributes:
2958
2959 eof_index - index of EOF, or -1
2960 timeout_index - index of TIMEOUT, or -1
2961
2962 After a successful match by the search() method the following attributes
2963 are available:
2964
2965 start - index into the buffer, first byte of match
2966 end - index into the buffer, first byte after match
2967 match - the re.match object returned by a succesful re.search
2968
2969 Args:
2970 patterns: 'patterns' to search. Where 'patterns' may be a list or other
2971 sequence of compiled regular expressions, or the EOF or TIMEOUT
2972 types.
2973 """
2974
2975 def __init__(self, patterns):
2976 self.eof_index = -1
2977 self.timeout_index = -1
2978 self._searches = []
2979 for n, s in zip(list(range(len(patterns))), patterns):
2980 if s is EOF:
2981 self.eof_index = n
2982 continue
2983 if s is TIMEOUT:
2984 self.timeout_index = n
2985 continue
2986 self._searches.append((n, s))
2987
2988 def __str__(self):
2989 """Return a human-readable string that represents the state of the object."""
2990 ss = [(n, f' {n}: re.compile(r"{s.pattern!s}")') for n, s in self._searches]
2991 ss.append((-1, "SearcherRegex:"))
2992 if self.eof_index >= 0:
2993 ss.append((self.eof_index, f" {self.eof_index}: EOF"))
2994 if self.timeout_index >= 0:
2995 ss.append((self.timeout_index, f" {self.timeout_index}: TIMEOUT"))
2996 ss.sort()
2997 ss = list(zip(*ss))[1]
2998 return "\n".join(ss)
2999
3000 def search(self, buffer, freshlen, searchwindowsize=None):
3001 """Search 'buffer' for the first occurence of one of the regular expressions.
3002
3003 'freshlen' must indicate the number of bytes at the end of 'buffer' which have
3004 not been searched before.
3005
3006 See class spawn for the 'searchwindowsize' argument.
3007
3008 If there is a match this returns the index of that string, and sets 'start',
3009 'end' and 'match'. Otherwise, returns -1.
3010 """
3011 absurd_match = len(buffer)
3012 first_match = absurd_match
3013 the_match = None
3014 best_index = None
3015 # 'freshlen' doesn't help here -- we cannot predict the
3016 # length of a match, and the re module provides no help.
3017 if searchwindowsize is None:
3018 searchstart = 0
3019 else:
3020 searchstart = max(0, len(buffer) - searchwindowsize)
3021 for index, s in self._searches:
3022 match = s.search(buffer, searchstart)
3023 if match is None:
3024 continue
3025 n = match.start()
3026 if n < first_match:
3027 first_match = n
3028 the_match = match
3029 best_index = index
3030 if first_match == absurd_match:
3031 return -1
3032 self.start = first_match
3033 self.match = the_match
3034 self.end = self.match.end()
3035 return best_index
3036
3037
3038 def log(e, suffix="", logdir=None):
3039 if isinstance(e, Exception):
3040 # Get the full traceback
3041 e = traceback.format_exc()
3042 # if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
3043 # # Only try to print if stdout is a tty, otherwise we might get
3044 # # an 'invalid handle' exception
3045 # print e
3046 if not logdir:
3047 if getattr(sys, "frozen", False):
3048 logdir = APPNAME
3049 else:
3050 logdir = os.path.split(os.path.dirname(os.path.abspath(__file__)))
3051 if logdir[-1] == "lib":
3052 logdir.pop()
3053 logdir = logdir[-1]
3054 if sys.platform == "win32":
3055 parent = SHGetSpecialFolderPath(0, CSIDL_APPDATA, 1)
3056 elif sys.platform == "darwin":
3057 parent = os.path.join(os.path.expanduser("~"), "Library", "Logs")
3058 else:
3059 parent = os.getenv("XDG_DATA_HOME", os.path.expandvars("$HOME/.local/share"))
3060 # If old user data directory exists, use its basename
3061 if logdir == APPNAME and os.path.isdir(os.path.join(parent, "dispcalGUI")):
3062 logdir = "dispcalGUI"
3063 logdir = os.path.join(parent, logdir)
3064 if sys.platform != "darwin":
3065 logdir = os.path.join(logdir, "logs")
3066 if not os.path.exists(logdir):
3067 with contextlib.suppress(OSError):
3068 os.makedirs(logdir)
3069 if os.path.isdir(logdir) and os.access(logdir, os.W_OK):
3070 logfile = os.path.join(logdir, f"wexpect{suffix}.log")
3071 if os.path.isfile(logfile):
3072 try:
3073 logstat = os.stat(logfile)
3074 except Exception:
3075 pass
3076 else:
3077 try:
3078 mtime = time.localtime(logstat.st_mtime)
3079 except ValueError:
3080 # This can happen on Windows because localtime() is buggy on
3081 # that platform. See:
3082 # http://stackoverflow.com/questions/4434629/zipfile-module-in-python-runtime-problems
3083 # http://bugs.python.org/issue1760357
3084 # To overcome this problem, we ignore the real modification
3085 # date and force a rollover
3086 mtime = time.localtime(time.time() - 60 * 60 * 24)
3087 if time.localtime()[:3] > mtime[:3]:
3088 # do rollover
3089 with contextlib.suppress(Exception):
3090 os.remove(logfile)
3091 try:
3092 with open(logfile, "a", encoding="utf-8") as fout:
3093 ts = time.time()
3094 fout.write(
3095 "{},{} {}\n".format(
3096 time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)),
3097 ("%3f" % (ts - int(ts)))[2:5],
3098 e,
3099 )
3100 )
3101 except Exception:
3102 pass
3103
3104
3105 def excepthook(etype, value, tb):
3106 log("".join(traceback.format_exception(etype, value, tb)))
3107
3108
3109 # sys.excepthook = excepthook
3110
3111
3112 def which(filename):
3113 """Try to find the given filename in the environment path.
3114
3115 Then check if it is executable. Return the full path to the filename
3116 if found and executable. Otherwise return None.
3117 """
3118 # Special case where filename already contains a path.
3119 if os.path.dirname(filename) != "" and os.access(filename, os.X_OK):
3120 return filename
3121
3122 if "PATH" not in os.environ or os.environ["PATH"] == "":
3123 p = os.defpath
3124 else:
3125 p = os.environ["PATH"]
3126
3127 # Oddly enough this was the one line that made Pexpect
3128 # incompatible with Python 1.5.2.
3129 # pathlist = p.split (os.pathsep)
3130 pathlist = string.split(p, os.pathsep)
3131
3132 for path in pathlist:
3133 f = os.path.join(path, filename)
3134 if os.access(f, os.X_OK):
3135 return f
3136 return None
3137
3138
3139 def join_args(args):
3140 """Join arguments into a command line.
3141
3142 It quotes all arguments that contain spaces or any of the characters:
3143
3144 ^!$%&()[]{}=;'+,`~
3145 """
3146 command_line = []
3147 for arg in args:
3148 if isinstance(arg, bytes):
3149 arg = arg.decode()
3150 if re.search(r"[^!$%&()[]{}=;'+,`~\s]", arg):
3151 arg = f'"{arg}"'
3152 command_line.append(arg)
3153 return " ".join(command_line)
3154
3155
3156 def split_command_line(command_line):
3157 """Split a command line into a list of arguments.
3158
3159 It splits arguments on spaces, but handles embedded quotes, doublequotes,
3160 and escaped characters. It's impossible to do this with a regular
3161 expression, so I wrote a little state machine to parse the command line.
3162 """
3163 arg_list = []
3164 arg = ""
3165
3166 # Constants to name the states we can be in.
3167 state_basic = 0
3168 state_esc = 1
3169 state_singlequote = 2
3170 state_doublequote = 3
3171 state_whitespace = 4 # The state of consuming whitespace between commands.
3172 state = state_basic
3173 state_backup = state
3174
3175 for c in command_line:
3176 if (
3177 state not in (state_esc, state_singlequote) and c == "\\"
3178 ): # Escape the next character
3179 state_backup = state
3180 state = state_esc
3181 elif state in [state_basic, state_whitespace]:
3182 if c == r"'": # Handle single quote
3183 state = state_singlequote
3184 elif c == r'"': # Handle double quote
3185 state = state_doublequote
3186 elif c.isspace():
3187 # Add arg to arg_list if we aren't in the middle of whitespace.
3188 if state != state_whitespace:
3189 arg_list.append(arg)
3190 arg = ""
3191 state = state_whitespace
3192 else:
3193 arg = arg + c
3194 state = state_basic
3195 elif state == state_esc:
3196 # Follow bash escaping rules within double quotes:
3197 # http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
3198 if state_backup == state_doublequote and c not in (
3199 "$",
3200 "`",
3201 '"',
3202 "\\",
3203 "\n",
3204 ):
3205 arg += "\\"
3206 arg = arg + c
3207 state = state_backup if state_backup != state_whitespace else state_basic
3208 elif state == state_singlequote:
3209 state = state_basic if c == r"'" else arg + c
3210 elif state == state_doublequote:
3211 if c == r'"':
3212 state = state_basic
3213 else:
3214 arg = arg + c
3215
3216 if arg != "":
3217 arg_list.append(arg)
3218 return arg_list