user791953
user791953

Reputation: 639

Issuing commands to psuedo shells (pty)

I've tried to use the subprocess, popen, os.spawn to get a process running, but it seems as though a pseudo terminal is needed.

import pty

(master, slave) = pty.openpty()

os.write(master, "ls -l")

Should send "ls -l" to the slave tty... I tried to read the response os.read(master, 1024), but nothing was available.

EDIT:

Also tried to create pty's, then open the call in a subprocess -- still didn't work.

import pty
import subprocess

(master, slave) = os.openpty()
p = subprocess.Popen("ls", close_fds=True, shell=slave, stdin=slave, stdout=slave)

Similar:

Send command and exit using python pty pseudo terminal process

How do *nix pseudo-terminals work ? What's the master/slave channel?

Upvotes: 0

Views: 4021

Answers (1)

that other guy
that other guy

Reputation: 123440

Use pty.spawn instead of os.spawn. Here's a function that runs a command in a separate pty and returns its output as a string:

import os
import pty

def inpty(argv):
  output = []
  def reader(fd):
    c = os.read(fd, 1024)
    while c:
      output.append(c)
      c = os.read(fd, 1024)

  pty.spawn(argv, master_read=reader)
  return ''.join(output)

print "Command output: " + inpty(["ls", "-l"])

Upvotes: 2

Related Questions