本文整理汇总了Python中pty.openpty函数的典型用法代码示例。如果您正苦于以下问题:Python openpty函数的具体用法?Python openpty怎么用?Python openpty使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了openpty函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self):
try:
# use a pty. This enforces unbuffered output and thus
# allows for fast update
master_out_fd, slave_out_fd = pty.openpty()
master_in_fd, self.slave_in_fd = pty.openpty()
self.proc = subprocess.Popen(self.cmd, stdin=master_in_fd, stdout=slave_out_fd, stderr=slave_out_fd)
except:
self.finished.emit(False)
return
# listen to process' output
while self.proc.poll() == None:
try:
if select.select([master_out_fd], [], [master_out_fd], .1)[0]:
output = os.read(master_out_fd, 100)
if output: self.output(str(output, "utf-8"))
except InterruptedError:
pass
os.close(master_out_fd)
os.close(slave_out_fd)
os.close(master_in_fd)
os.close(self.slave_in_fd)
self.finished.emit(self.proc.wait() == 0)
示例2: __init__
def __init__(self, ip=get_ipython()):
# For the registration
self.shell = ip
self.nbOutStream = sys.stdout
self.nbErrStream = sys.stderr
self.pyOutStream = sys.__stdout__
self.pyErrStream = sys.__stderr__
self.outStreamPipe_in = pty.openpty()[1]
self.errStreamPipe_in = pty.openpty()[1]
os.dup2(self.outStreamPipe_in, self.pyOutStream.fileno())
os.dup2(self.errStreamPipe_in, self.pyErrStream.fileno())
self.ioHandler = handlers.IOHandler()
self.flag = True
self.outString = ""
self.errString = ""
self.asyncCapturer = handlers.Runner(self.syncCapture)
self.isFirstPreExecute = True
self.isFirstPostExecute = True
示例3: __init__
def __init__(self, cmd, capturestderr=False, bufsize=-1):
""" Popen3 class (isn't this actually Popen4, capturestderr = False?) that uses ptys
instead of pipes, to allow inline reading (instead of potential i/o buffering) of
output from the child process. It also stores the cmd its running (as a string)
and the thread that created the object, for later use """
import pty
# NOTE: most of this is cutnpaste from Popen3 minus the openpty calls
# popen2._cleanup()
self.prettyCmd = cmd
cmd = self.parseCmdToList(cmd)
self.cmd = cmd
self.threadIdent = thread.get_ident()
p2cread, p2cwrite = pty.openpty()
c2pread, c2pwrite = pty.openpty()
if capturestderr:
errout, errin = pty.openpty()
self.pid = os.fork()
if self.pid == 0:
# Child
os.dup2(p2cread, 0)
os.dup2(c2pwrite, 1)
if capturestderr:
os.dup2(errin, 2)
self._run_child(cmd)
os.close(p2cread)
self.tochild = os.fdopen(p2cwrite, "w", bufsize)
os.close(c2pwrite)
self.fromchild = os.fdopen(c2pread, "r", bufsize)
if capturestderr:
os.close(errin)
self.childerr = os.fdopen(errout, "r", bufsize)
else:
self.childerr = None
示例4: mkpty
def mkpty():
master1, slave = pty.openpty()
slaveName1 = os.ttyname(slave)
master2, slave = pty.openpty()
slaveName2 = os.ttyname(slave)
print '\nslave device names: ', slaveName1, slaveName2
return master1, master2
示例5: tty_capture
def tty_capture(cmd, bytes_input):
"""Capture the output of cmd with bytes_input to stdin,
with stdin, stdout and stderr as TTYs."""
mo, so = pty.openpty() # provide tty to enable line-buffering
me, se = pty.openpty()
mi, si = pty.openpty()
fdmap = {mo: 'stdout', me: 'stderr', mi: 'stdin'}
p = subprocess.Popen(
cmd, bufsize=1, stdin=si, stdout=so, stderr=se, close_fds=True)
os.write(mi, bytes_input)
timeout = .04 # seconds
res = {'stdout': b'', 'stderr': b''}
while True:
ready, _, _ = select.select([mo, me], [], [], timeout)
if ready:
for fd in ready:
data = os.read(fd, 512)
if not data:
break
res[fdmap[fd]] += data
elif p.poll() is not None: # select timed-out
break # p exited
for fd in [si, so, se, mi, mo, me]:
os.close(fd) # can't do it sooner: it leads to errno.EIO error
p.wait()
return p.returncode, res['stdout'], res['stderr']
示例6: __open_process
def __open_process(self, logger, cmd, env, cwd, **kwargs):
if logger:
logger.info('Running command: %r' % cmd)
if env:
logger.info('With env (showing only all caps):')
for key, val in env.iteritems():
if re.match(r'[A-Z0-9_]+', key):
logger.info(' %-20s = %s' % (key,val))
logger.info('With CWD: %s' % (cwd or os.getcwd()))
logger.info('-' * 100)
# provide tty to enable line buffering.
master_out_fd, slave_out_fd = pty.openpty()
master_err_fd, slave_err_fd = pty.openpty()
process = subprocess.Popen(
cmd,
cwd=cwd,
env=env,
shell=False,
bufsize=1,
stderr=slave_err_fd,
stdout=slave_out_fd,
close_fds=True)
return (process, (master_out_fd, slave_out_fd), (master_err_fd, slave_err_fd))
示例7: __init__
def __init__(self, args, cwd=None, env=None, stdin=False,
echo_stdout=True, echo_stderr=True,
capture_stdout=False, capture_stderr=False):
if cwd is not None:
cwd = str(cwd)
logging.debug('Running {}...'.format(args[0]))
logging.debug('Parameters: {}'.format(args))
logging.debug('Working directory: {}'.format(cwd))
logging.debug('Environment: {}'.format(env))
logging.debug('Echo: stdout: {}, stderr: {}'.format(echo_stdout, echo_stderr))
self.args = args
self.buffer_stdout = bytearray()
self.buffer_stderr = bytearray()
master_stdout, slave_stdout = pty.openpty()
master_stderr, slave_stderr = pty.openpty()
Process.set_nonblocking(master_stdout)
Process.set_nonblocking(master_stderr)
self.process = subprocess.Popen(args, bufsize=0, cwd=cwd, env=env,
stdin=stdin, stdout=slave_stdout, stderr=slave_stderr)
pass_to_stdout = sys.stdout.buffer if echo_stdout else None
pass_to_stderr = sys.stderr.buffer if echo_stderr else None
self._reader_stdout = self.reader(master_stdout, capture_stdout,
self.buffer_stdout, pass_to_stdout)
self._reader_stderr = self.reader(master_stderr, capture_stderr,
self.buffer_stderr, pass_to_stderr)
示例8: _create_pty_or_pipe
def _create_pty_or_pipe(copy_term_size=None):
"""
Try to create a pty and if then fails then create a normal
pipe instead.
@param copy_term_size: If a tty file descriptor is given
then the term size will be copied to the pty.
@type copy_term_size: int
@rtype: tuple
@returns: A tuple of (is_pty, master_fd, slave_fd) where
is_pty is True if a pty was successfully allocated, and
False if a normal pipe was allocated.
"""
got_pty = False
global _disable_openpty, _fbsd_test_pty
if _fbsd_test_pty and not _disable_openpty:
# Test for python openpty breakage after freebsd7 to freebsd8
# upgrade, which results in a 'Function not implemented' error
# and the process being killed.
pid = os.fork()
if pid == 0:
pty.openpty()
os._exit(os.EX_OK)
pid, status = os.waitpid(pid, 0)
if (status & 0xff) == 140:
_disable_openpty = True
_fbsd_test_pty = False
if _disable_openpty:
master_fd, slave_fd = os.pipe()
else:
try:
master_fd, slave_fd = pty.openpty()
got_pty = True
except EnvironmentError as e:
_disable_openpty = True
writemsg("openpty failed: '%s'\n" % str(e),
noiselevel=-1)
del e
master_fd, slave_fd = os.pipe()
if got_pty:
# Disable post-processing of output since otherwise weird
# things like \n -> \r\n transformations may occur.
mode = termios.tcgetattr(slave_fd)
mode[1] &= ~termios.OPOST
termios.tcsetattr(slave_fd, termios.TCSANOW, mode)
if got_pty and \
copy_term_size is not None and \
os.isatty(copy_term_size):
rows, columns = get_term_size()
set_term_size(rows, columns, slave_fd)
return (got_pty, master_fd, slave_fd)
示例9: _execute_process_pty
def _execute_process_pty(cmd, cwd, env, shell, stderr_to_stdout=True):
stdout_master, stdout_slave = None, None
stderr_master, stderr_slave = None, None
fds_to_close = [stdout_master, stdout_slave, stderr_master, stderr_slave]
try:
stdout_master, stdout_slave = pty.openpty()
if stderr_to_stdout:
stderr_master, stderr_slave = stdout_master, stdout_slave
else:
stderr_master, stderr_slave = pty.openpty()
p = None
while p is None:
try:
p = Popen(
cmd,
stdin=stdout_slave, stdout=stderr_slave, stderr=STDOUT,
cwd=cwd, env=env, shell=shell, close_fds=False)
except OSError as exc:
# This can happen if a file you are trying to execute is being
# written to simultaneously on Linux
# (doesn't appear to happen on OS X)
# It seems like the best strategy is to just try again later
# Worst case is that the file eventually gets deleted, then a
# different OSError would occur.
if 'Text file busy' in '{0}'.format(exc):
# This is a transient error, try again shortly
time.sleep(0.01)
continue
raise
# This causes the below select to exit when the subprocess closes.
# On Linux, this sometimes causes Errno 5 OSError's when os.read
# is called from within _yield_data, so on Linux _yield_data
# catches and passes on that particular OSError.
os.close(stdout_slave)
if not stderr_to_stdout:
os.close(stderr_slave)
left_overs = {stdout_master: b'', stderr_master: b''}
fds = [stdout_master]
if stderr_master != stdout_master:
fds.append(stderr_master)
finally:
# Make sure we don't leak file descriptors
_close_fds(fds_to_close)
# The linesep with pty's always seems to be "\r\n", even on OS X
return _yield_data(p, fds, left_overs, "\r\n", fds_to_close)
示例10: run
def run(self):
self.ioloop = IOLoop.instance()
(master_fd, slave_fd) = pty.openpty()
# make stdout, stderr non-blocking
fcntl.fcntl(master_fd, fcntl.F_SETFL,
fcntl.fcntl(master_fd, fcntl.F_GETFL) | os.O_NONBLOCK)
self.master_fd = master_fd
self.master = os.fdopen(master_fd)
# listen to stdout, stderr
self.ioloop.add_handler(master_fd, self._handle_subprocess_stdout,
self.ioloop.READ)
slave = os.fdopen(slave_fd)
self.kwargs["stdout"] = slave
self.kwargs["stderr"] = slave
self.kwargs["close_fds"] = True
self.pipe = subprocess.Popen(*self.args, **self.kwargs)
self.stdin = self.pipe.stdin
# check for process exit
self.wait_callback = PeriodicCallback(self._wait_for_end, 250)
self.wait_callback.start()
示例11: __init__
def __init__(self, cmd, logger):
self.thread = threading.Thread(target=TestProcess._run, args=(weakref.proxy(self),))
self.pty_master, self.pty_slave = pty.openpty()
self.logger = logger
self.process = None
self.traces = ""
self.cmd = cmd
示例12: call_and_peek_output
def call_and_peek_output(cmd, shell=False):
import pty
import subprocess
master, slave = pty.openpty()
print cmd
p = subprocess.Popen(cmd, shell=shell, stdin=None, stdout=slave, close_fds=True)
os.close(slave)
line = ""
while True:
try:
ch = os.read(master, 1)
except OSError:
# We get this exception when the spawn process closes all references to the
# pty descriptor which we passed him to use for stdout
# (typically when it and its childs exit)
break
line += ch
if ch == '\n':
yield line
line = ""
if line:
yield line
ret = p.wait()
if ret:
raise subprocess.CalledProcessError(ret, cmd)
示例13: spawn
def spawn(self, argv=None, term=None):
if argv is None:
if "SHELL" in os.environ:
argv = [os.environ["SHELL"]]
elif "PATH" in os.environ: # searching sh in the path. It can be unusual like /system/bin/sh on android
for shell in ["bash", "sh", "ksh", "zsh", "csh", "ash"]:
for path in os.environ["PATH"].split(":"):
fullpath = os.path.join(path.strip(), shell)
if os.path.isfile(fullpath):
argv = [fullpath]
break
if argv:
break
if not argv:
argv = ["/bin/sh"]
if term is not None:
os.environ["TERM"] = term
master, slave = pty.openpty()
self.slave = slave
self.master = os.fdopen(master, "rb+wb", 0) # open file in an unbuffered mode
flags = fcntl.fcntl(self.master, fcntl.F_GETFL)
assert flags >= 0
flags = fcntl.fcntl(self.master, fcntl.F_SETFL, flags | os.O_NONBLOCK)
assert flags >= 0
self.prog = subprocess.Popen(
shell=False, args=argv, stdin=slave, stdout=slave, stderr=subprocess.STDOUT, preexec_fn=prepare
)
示例14: __init_streams
def __init_streams(self, stdin, stdout, stderr, unbuffered):
self.stdin = self.stdout = self.stderr = None
if unbuffered:
master, slave = pty.openpty()
if stdin is PIPE:
self._child_stdin, self._stdin = (slave, master) if unbuffered else os.pipe()
self.stdin = os.fdopen(self._stdin, 'w')
elif isinstance(stdin, int):
self._child_stdin, self._stdin = stdin, -1
elif stdin is not None:
self._child_stdin, self._stdin = stdin.fileno(), -1
else:
self._child_stdin = self._stdin = -1
if stdout is PIPE:
self._stdout, self._child_stdout = (master, slave) if unbuffered else os.pipe()
self.stdout = os.fdopen(self._stdout, 'r')
elif isinstance(stdout, int):
self._stdout, self._child_stdout = -1, stdout
elif stdout is not None:
self._stdout, self._child_stdout = -1, stdout.fileno()
else:
self._stdout = self._child_stdout = -1
if stderr is PIPE:
self._stderr, self._child_stderr = os.pipe()
self.stderr = os.fdopen(self._stderr, 'r')
elif isinstance(stderr, int):
self._stderr, self._child_stderr = -1, stderr
elif stderr is not None:
self._stderr, self._child_stderr = -1, stderr.fileno()
else:
self._stderr = self._child_stderr = -1
示例15: _has_sudo
def _has_sudo(self, result):
_master, slave = pty.openpty()
os.setsid()
fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
out, err, exit = run_command(['sudo', '-l', '-U', self.user[USER_NAME],
'sudo'])
if exit == 0:
debug("User %s is allowed to run sudo" % self.user[USER_NAME])
# sudo allows a wide range of configurations, such as controlling
# which binaries the user can execute with sudo.
# For now, we will just check whether the user is allowed to run
# any command with sudo.
out, err, exit = run_command(['sudo', '-l', '-U',
self.user[USER_NAME]])
for line in out.split('\n'):
if line and re.search("(ALL)", line):
result.value = 1
debug("User %s can run any command with sudo" %
result.value)
return
debug("User %s can only run some commands with sudo" %
self.user[USER_NAME])
else:
debug("User %s is not allowed to run sudo" % self.user[USER_NAME])