本文整理匯總了Python中pty.fork方法的典型用法代碼示例。如果您正苦於以下問題:Python pty.fork方法的具體用法?Python pty.fork怎麽用?Python pty.fork使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pty
的用法示例。
在下文中一共展示了pty.fork方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def __init__(self, args, close_stderr=False):
pid, fd = pty.fork()
if pid == 0:
# We're the child. Transfer control to command.
if close_stderr:
dev_null = os.open('/dev/null', 0)
os.dup2(dev_null, 2)
os.execvp(args[0], args)
else:
# Disable echoing.
attr = termios.tcgetattr(fd)
attr[3] = attr[3] & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, attr)
# Set up a file()-like interface to the child process
self.r = os.fdopen(fd, 'r', 1)
self.w = os.fdopen(os.dup(fd), 'w', 1)
示例2: SpawnPTY
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def SpawnPTY(argv):
"""Spawn a process and connect its controlling terminal to a PTY.
Create a new PTY device and spawn a process with the controlling
terminal of the child process set to the slave end of the new PTY.
Args:
argv: arguments (including executable name) for the child process.
Returns:
A pair containing the PID of the child process and the file
descriptor for the master end of the new PTY device.
"""
assert argv, 'SpawnPTY: argv is an empty list'
(pid, fd) = pty.fork()
if pid == 0:
try:
os.execvp(argv[0], argv)
except OSError as err:
print "# Error: cannot execute program '%s'" % argv[0]
print '# %s\n%s' % (str(err), chr(4))
sys.exit(1)
return (pid, fd)
示例3: spawn
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def spawn(self):
env = self.env
env['TERM'] = 'linux'
self.pid, self.master = pty.fork()
if self.pid == 0:
if callable(self.command):
try:
try:
self.command()
except:
sys.stderr.write(traceback.format_exc())
sys.stderr.flush()
finally:
os._exit(0)
else:
os.execvpe(self.command[0], self.command, env)
if self.main_loop is None:
fcntl.fcntl(self.master, fcntl.F_SETFL, os.O_NONBLOCK)
atexit.register(self.terminate)
示例4: handle
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def handle(self):
masterFd, slaveFd = pty.openpty()
try:
# if we're not in the main thread, this will not work.
signal.signal(signal.SIGTTOU, signal.SIG_IGN)
except: # noqa
pass
pid = os.fork()
if pid:
os.close(masterFd)
raise SocketConnected(slaveFd, pid)
# make parent process the pty slave - the opposite of
# pty.fork(). In this setup, the parent process continues
# to act normally, while the child process performs the
# logging. This makes it simple to kill the logging process
# when we are done with it and restore the parent process to
# normal, unlogged operation.
else:
os.close(slaveFd)
try:
protocol = TelnetServerProtocolHandler(self.request, masterFd)
protocol.handle()
finally:
os.close(masterFd)
os._exit(1)
示例5: test_child_gets_controlling_tty_if_we_had_one
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def test_child_gets_controlling_tty_if_we_had_one():
"""If dumb-init has a controlling TTY, it should give it to the child.
To test this, we make a new TTY then exec "dumb-init bash" and ensure that
the shell has working job control.
"""
pid, sfd = pty.fork()
if pid == 0:
os.execvp('dumb-init', ('dumb-init', 'bash', '-m'))
else:
ttyflags(sfd)
# We might get lots of extra output from the shell, so print something
# we can match on easily.
assert os.write(sfd, b'echo "flags are: [[$-]]"\n') == 25
assert os.write(sfd, b'exit 0\n') == 7
output = readall(sfd)
assert os.waitpid(pid, 0) == (pid, 0), output
m = re.search(b'flags are: \\[\\[([a-zA-Z]+)\\]\\]\n', output)
assert m, output
# "m" is job control
flags = m.group(1)
assert b'm' in flags
示例6: __init__
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def __init__(self, cmd, cwd):
self._cmd_return_code = 0
self._cmd_kill_signal = 0
self._shell_pid, self._master_fd = pty.fork()
if self._shell_pid == pty.CHILD:
os.environ["TERM"] = "linux"
os.chdir(cwd)
os.execv(cmd[0], cmd)
示例7: __fork_pty
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def __fork_pty(self):
"""This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue with Python's pty.fork() not supporting Solaris,
particularly ssh. Based on patch to posixmodule.c authored by Noah
Spurrier::
http://mail.python.org/pipermail/python-dev/2003-May/035281.html
"""
parent_fd, child_fd = os.openpty()
if parent_fd < 0 or child_fd < 0:
raise ExceptionPexpect("Error! Could not open pty with os.openpty().")
pid = os.fork()
if pid < 0:
raise ExceptionPexpect("Error! Failed os.fork().")
elif pid == 0:
# Child.
os.close(parent_fd)
self.__pty_make_controlling_tty(child_fd)
os.dup2(child_fd, 0)
os.dup2(child_fd, 1)
os.dup2(child_fd, 2)
if child_fd > 2:
os.close(child_fd)
else:
# Parent.
os.close(child_fd)
return pid, parent_fd
示例8: read_until_semaphore
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def read_until_semaphore(fd, semaphore=RECV_SEMAPHORE,
encoding='utf8', timeout=10):
"""Read file descriptor ``fd`` until ``semaphore`` is found.
Used to ensure the child process is awake and ready. For timing
tests; without a semaphore, the time to fork() would be (incorrectly)
included in the duration of the test, which can be very length on
continuous integration servers (such as Travis-CI).
"""
# note that when a child process writes xyz\\n, the parent
# process will read xyz\\r\\n -- this is how pseudo terminals
# behave; a virtual terminal requires both carriage return and
# line feed, it is only for convenience that \\n does both.
outp = six.text_type()
decoder = codecs.getincrementaldecoder(encoding)()
semaphore = semaphore.decode('ascii')
while not outp.startswith(semaphore):
try:
_exc = os.read(fd, 1)
except OSError: # Linux EOF
break
if not _exc: # BSD EOF
break
outp += decoder.decode(_exc, final=False)
assert outp.startswith(semaphore), (
'Semaphore not recv before EOF '
'(expected: %r, got: %r)' % (semaphore, outp,))
return outp[len(semaphore):]
示例9: __fork_pty
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def __fork_pty(self):
"""This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue with Python's pty.fork() not supporting Solaris,
particularly ssh. Based on patch to posixmodule.c authored by Noah
Spurrier::
http://mail.python.org/pipermail/python-dev/2003-May/035281.html
"""
parent_fd, child_fd = os.openpty()
if parent_fd < 0 or child_fd < 0:
raise ExceptionPexpect, "Error! Could not open pty with os.openpty()."
pid = os.fork()
if pid < 0:
raise ExceptionPexpect, "Error! Failed os.fork()."
elif pid == 0:
# Child.
os.close(parent_fd)
self.__pty_make_controlling_tty(child_fd)
os.dup2(child_fd, 0)
os.dup2(child_fd, 1)
os.dup2(child_fd, 2)
if child_fd > 2:
os.close(child_fd)
else:
# Parent.
os.close(child_fd)
return pid, parent_fd
示例10: __fork_pty
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def __fork_pty(self):
'''This implements a substitute for the forkpty system call. This
should be more portable than the pty.fork() function. Specifically,
this should work on Solaris.
Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
resolve the issue with Python's pty.fork() not supporting Solaris,
particularly ssh. Based on patch to posixmodule.c authored by Noah
Spurrier::
http://mail.python.org/pipermail/python-dev/2003-May/035281.html
'''
parent_fd, child_fd = os.openpty()
if parent_fd < 0 or child_fd < 0:
raise ExceptionPexpect("Could not open with os.openpty().")
pid = os.fork()
if pid == pty.CHILD:
# Child.
os.close(parent_fd)
self.__pty_make_controlling_tty(child_fd)
os.dup2(child_fd, self.STDIN_FILENO)
os.dup2(child_fd, self.STDOUT_FILENO)
os.dup2(child_fd, self.STDERR_FILENO)
else:
# Parent.
os.close(child_fd)
return pid, parent_fd
示例11: __pty_make_controlling_tty
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def __pty_make_controlling_tty(self, tty_fd):
'''This makes the pseudo-terminal the controlling tty. This should be
more portable than the pty.fork() function. Specifically, this should
work on Solaris. '''
child_name = os.ttyname(tty_fd)
# Disconnect from controlling tty, if any. Raises OSError of ENXIO
# if there was no controlling tty to begin with, such as when
# executed by a cron(1) job.
try:
fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
os.close(fd)
except OSError as err:
if err.errno != errno.ENXIO:
raise
os.setsid()
# Verify we are disconnected from controlling tty by attempting to open
# it again. We expect that OSError of ENXIO should always be raised.
try:
fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
os.close(fd)
raise ExceptionPexpect("OSError of errno.ENXIO should be raised.")
except OSError as err:
if err.errno != errno.ENXIO:
raise
# Verify we can open child pty.
fd = os.open(child_name, os.O_RDWR)
os.close(fd)
# Verify we now have a controlling tty.
fd = os.open("/dev/tty", os.O_WRONLY)
os.close(fd)
示例12: _spawn
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def _spawn(shell, master_read):
"""Create a spawned process.
Modified version of pty.spawn with terminal size support.
"""
pid, master_fd = pty.fork()
if pid == pty.CHILD:
os.execlp(shell, shell)
try:
mode = tty.tcgetattr(pty.STDIN_FILENO)
tty.setraw(pty.STDIN_FILENO)
restore = True
except tty.error: # This is the same as termios.error
restore = False
_set_pty_size(master_fd)
signal.signal(signal.SIGWINCH, lambda *_: _set_pty_size(master_fd))
try:
pty._copy(master_fd, master_read, pty._read)
except OSError:
if restore:
tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, mode)
os.close(master_fd)
return os.waitpid(pid, 0)[1]
示例13: read_until_semaphore
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def read_until_semaphore(fd, semaphore=RECV_SEMAPHORE,
encoding='utf8', timeout=10):
"""Read file descriptor ``fd`` until ``semaphore`` is found.
Used to ensure the child process is awake and ready. For timing
tests; without a semaphore, the time to fork() would be (incorrectly)
included in the duration of the test, which can be very length on
continuous integration servers (such as Travis-CI).
"""
# note that when a child process writes xyz\\n, the parent
# process will read xyz\\r\\n -- this is how pseudo terminals
# behave; a virtual terminal requires both carriage return and
# line feed, it is only for convenience that \\n does both.
outp = unicode()
decoder = codecs.getincrementaldecoder(encoding)()
semaphore = semaphore.decode('ascii')
while not outp.startswith(semaphore):
try:
_exc = os.read(fd, 1)
except OSError: # Linux EOF
break
if not _exc: # BSD EOF
break
outp += decoder.decode(_exc, final=False)
assert outp.startswith(semaphore), (
'Semaphore not recv before EOF '
'(expected: %r, got: %r)' % (semaphore, outp,))
return outp[len(semaphore):]
示例14: test_kbhit_interrupted
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def test_kbhit_interrupted():
"kbhit() should not be interrupted with a signal handler."
pid, master_fd = pty.fork()
if pid is 0:
try:
cov = __import__('cov_core_init').init()
except ImportError:
cov = None
# child pauses, writes semaphore and begins awaiting input
global got_sigwinch
got_sigwinch = False
def on_resize(sig, action):
global got_sigwinch
got_sigwinch = True
term = TestTerminal()
signal.signal(signal.SIGWINCH, on_resize)
read_until_semaphore(sys.__stdin__.fileno(), semaphore=SEMAPHORE)
os.write(sys.__stdout__.fileno(), SEMAPHORE)
with term.raw():
assert term.inkey(timeout=1.05) == u''
os.write(sys.__stdout__.fileno(), b'complete')
assert got_sigwinch is True
if cov is not None:
cov.stop()
cov.save()
os._exit(0)
with echo_off(master_fd):
os.write(master_fd, SEND_SEMAPHORE)
read_until_semaphore(master_fd)
stime = time.time()
os.kill(pid, signal.SIGWINCH)
output = read_until_eof(master_fd)
pid, status = os.waitpid(pid, 0)
assert output == u'complete'
assert os.WEXITSTATUS(status) == 0
assert math.floor(time.time() - stime) == 1.0
示例15: test_inkey_cbreak_input_slowly
# 需要導入模塊: import pty [as 別名]
# 或者: from pty import fork [as 別名]
def test_inkey_cbreak_input_slowly():
"0-second inkey with input; Keypress should be immediately returned."
pid, master_fd = pty.fork()
if pid is 0:
try:
cov = __import__('cov_core_init').init()
except ImportError:
cov = None
# child pauses, writes semaphore and begins awaiting input
term = TestTerminal()
read_until_semaphore(sys.__stdin__.fileno(), semaphore=SEMAPHORE)
os.write(sys.__stdout__.fileno(), SEMAPHORE)
with term.cbreak():
while True:
inp = term.inkey(timeout=0.5)
os.write(sys.__stdout__.fileno(), inp.encode('utf-8'))
if inp == 'X':
break
if cov is not None:
cov.stop()
cov.save()
os._exit(0)
with echo_off(master_fd):
os.write(master_fd, SEND_SEMAPHORE)
os.write(master_fd, u'a'.encode('ascii'))
time.sleep(0.1)
os.write(master_fd, u'b'.encode('ascii'))
time.sleep(0.1)
os.write(master_fd, u'cdefgh'.encode('ascii'))
time.sleep(0.1)
os.write(master_fd, u'X'.encode('ascii'))
read_until_semaphore(master_fd)
stime = time.time()
output = read_until_eof(master_fd)
pid, status = os.waitpid(pid, 0)
assert output == u'abcdefghX'
assert os.WEXITSTATUS(status) == 0
assert math.floor(time.time() - stime) == 0.0