Issuing commands to psuedo shells (pty)

元气小坏坏 提交于 2021-02-04 21:34:22

问题


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?


回答1:


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"])


来源:https://stackoverflow.com/questions/21442360/issuing-commands-to-psuedo-shells-pty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!