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