CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
Ardupilot

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: Ardupilot/ardupilot
Path: blob/master/Tools/autotest/pysim/fdpexpect.py
Views: 1799
1
"""This is like pexpect, but will work on any file descriptor that you pass it.
2
So you are responsible for opening and close the file descriptor.
3
4
$Id: fdpexpect.py 505 2007-12-26 21:33:50Z noah $
5
"""
6
from __future__ import print_function
7
import os
8
9
from pexpect import ExceptionPexpect, spawn
10
11
__all__ = ['fdspawn']
12
13
14
class fdspawn(spawn):
15
"""This is like pexpect.spawn but allows you to supply your own open file
16
descriptor. For example, you could use it to read through a file looking
17
for patterns, or to control a modem or serial device. """
18
19
def __init__(self, fd, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None):
20
21
"""This takes a file descriptor (an int) or an object that support the
22
fileno() method (returning an int). All Python file-like objects
23
support fileno(). """
24
25
# TODO: Add better handling of trying to use fdspawn in place of spawn
26
# TODO: (overload to allow fdspawn to also handle commands as spawn does.
27
28
if not isinstance(fd, int) and hasattr(fd, 'fileno'):
29
fd = fd.fileno()
30
31
if not isinstance(fd, int):
32
raise ExceptionPexpect(
33
"The fd argument is not an int. If this is a command string then maybe you want to use pexpect.spawn.")
34
35
try: # make sure fd is a valid file descriptor
36
os.fstat(fd)
37
except OSError:
38
raise ExceptionPexpect("The fd argument is not a valid file descriptor.")
39
40
self.args = None
41
self.command = None
42
spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile)
43
self.child_fd = fd
44
self.own_fd = False
45
self.closed = False
46
self.name = '<file descriptor %d>' % fd
47
48
def __del__(self):
49
50
return
51
52
def close(self):
53
54
if self.child_fd == -1:
55
return
56
if self.own_fd:
57
self.close(self)
58
else:
59
self.flush()
60
os.close(self.child_fd)
61
self.child_fd = -1
62
self.closed = True
63
64
def isalive(self):
65
66
"""This checks if the file descriptor is still valid. If os.fstat()
67
does not raise an exception then we assume it is alive. """
68
69
if self.child_fd == -1:
70
return False
71
try:
72
os.fstat(self.child_fd)
73
return True
74
except:
75
return False
76
77
def terminate(self, force=False):
78
79
raise ExceptionPexpect('This method is not valid for file descriptors.')
80
81
def kill(self, sig):
82
83
return
84
85