]> git.ipfire.org Git - thirdparty/openembedded/openembedded-core.git/blob - scripts/oepydevshell-internal.py
python3: move dataclasses to python3-core
[thirdparty/openembedded/openembedded-core.git] / scripts / oepydevshell-internal.py
1 #!/usr/bin/env python3
2 #
3 # Copyright OpenEmbedded Contributors
4 #
5 # SPDX-License-Identifier: GPL-2.0-only
6 #
7
8 import os
9 import sys
10 import time
11 import select
12 import fcntl
13 import termios
14 import readline
15 import signal
16
17 def nonblockingfd(fd):
18 fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
19
20 def echonocbreak(fd):
21 old = termios.tcgetattr(fd)
22 old[3] = old[3] | termios.ECHO | termios.ICANON
23 termios.tcsetattr(fd, termios.TCSADRAIN, old)
24
25 def cbreaknoecho(fd):
26 old = termios.tcgetattr(fd)
27 old[3] = old[3] &~ termios.ECHO &~ termios.ICANON
28 termios.tcsetattr(fd, termios.TCSADRAIN, old)
29
30 if len(sys.argv) != 3 or sys.argv[1] in ('-h', '--help'):
31 print('oepydevshell-internal.py: error: the following arguments are required: pty, pid\n'
32 'Usage: oepydevshell-internal.py pty pid\n\n'
33 'OpenEmbedded oepydevshell-internal.py - internal script called from meta/classes/devshell.bbclass\n\n'
34 'arguments:\n'
35 ' pty pty device name\n'
36 ' pid parent process id\n\n'
37 'options:\n'
38 ' -h, --help show this help message and exit\n')
39 sys.exit(2)
40
41 pty = open(sys.argv[1], "w+b", 0)
42 parent = int(sys.argv[2])
43
44 nonblockingfd(pty)
45 nonblockingfd(sys.stdin)
46
47
48 histfile = os.path.expanduser("~/.oepydevshell-history")
49 readline.parse_and_bind("tab: complete")
50 try:
51 readline.read_history_file(histfile)
52 except IOError:
53 pass
54
55 try:
56
57 i = ""
58 o = ""
59 # Need cbreak/noecho whilst in select so we trigger on any keypress
60 cbreaknoecho(sys.stdin.fileno())
61 # Send our PID to the other end so they can kill us.
62 pty.write(str(os.getpid()).encode('utf-8') + b"\n")
63 while True:
64 try:
65 writers = []
66 if i:
67 writers.append(sys.stdout)
68 (ready, _, _) = select.select([pty, sys.stdin], writers , [], 0)
69 try:
70 if pty in ready:
71 readdata = pty.read()
72 if readdata:
73 i = i + readdata.decode('utf-8')
74 if i:
75 # Write a page at a time to avoid overflowing output
76 # d.keys() is a good way to do that
77 sys.stdout.write(i[:4096])
78 sys.stdout.flush()
79 i = i[4096:]
80 if sys.stdin in ready:
81 echonocbreak(sys.stdin.fileno())
82 o = input().encode('utf-8')
83 cbreaknoecho(sys.stdin.fileno())
84 pty.write(o + b"\n")
85 except (IOError, OSError) as e:
86 if e.errno == 11:
87 continue
88 if e.errno == 5:
89 sys.exit(0)
90 raise
91 except EOFError:
92 sys.exit(0)
93 except KeyboardInterrupt:
94 os.kill(parent, signal.SIGINT)
95
96 except SystemExit:
97 pass
98 except Exception as e:
99 import traceback
100 print("Exception in oepydehshell-internal: " + str(e))
101 traceback.print_exc()
102 time.sleep(5)
103 finally:
104 readline.write_history_file(histfile)