交互式,非阻塞的subprocess.Popen脚本,不使用communication或pexpect

时间:2015-08-19 01:31:00

标签: python subprocess popen

答:为什么阻止?

B:我如何按摩轻微以便它可以无阻塞地运行?

#!/usr/bin/env python
import subprocess as sp
import os

kwds = dict(
    stdin=sp.PIPE,
    stdout=sp.PIPE,
    stderr=sp.PIPE,
    cwd=os.path.abspath(os.getcwd()),
    shell=True,
    executable='/bin/bash',
    bufsize=1,
    universal_newlines=True,
)
cmd = '/bin/bash'
proc = sp.Popen(cmd, **kwds)
proc.stdin.write('ls -lashtr\n')
proc.stdin.flush()

# This blocks and never returns
proc.stdout.read()

我需要以交互方式运行。

这是一个简化的示例,但实际情况是我有一个漫长的运行过程,我想启动一个可以或多或少运行任意代码的shell脚本(因为它是一个安装脚本)

编辑: 我想在几个不同的登录中有效地使用.bash_history,清理它以便它是一个单独的脚本,然后在存储在Python脚本中的shell中逐行执行新制作的shell脚本。

例如:

> ... ssh to remote aws system ...
> sudo su -
> apt-get install stuff
> su - $USERNAME
> ... create and enter a docker snapshot ...
> ... install packages, update configurations
> ... install new services, update service configurations ...
> ... drop out of snapshot ...
> ... commit the snapshot ...
> ... remove the snapshot ...
> ... update services ...
> ... restart services ...
> ... drop into a tmux within the new docker ...

手动需要数小时;它应该是自动化的。

2 个答案:

答案 0 :(得分:0)

  

答:为什么会阻止?

它阻止,因为它是.read()的作用:它读取所有字节,直到文件结束指示。由于该过程从不指示文件结束,因此.read()永远不会返回。

  

B:我怎么可以稍微按摩一下(稍微强调一点),这样它就会毫无阻碍地运行?

要做的一件事是让进程指示文件结束。一个小小的改动就是让子进程退出。

proc.stdin.write('ls -lashtr; exit\n')

答案 1 :(得分:-1)

这是我的另一个答案的示例:https://stackoverflow.com/a/43012138/3555925,它没有使用pexpect。您可以在该答案中看到更多详细信息。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import select
import termios
import tty
import pty
from subprocess import Popen

command = 'bash'
# command = 'docker run -it --rm centos /bin/bash'.split()

# save original tty setting then set it to raw mode
old_tty = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())

# open pseudo-terminal to interact with subprocess
master_fd, slave_fd = pty.openpty()

# use os.setsid() make it run in a new process group, or bash job control will not be enabled
p = Popen(command,
          preexec_fn=os.setsid,
          stdin=slave_fd,
          stdout=slave_fd,
          stderr=slave_fd,
          universal_newlines=True)

while p.poll() is None:
    r, w, e = select.select([sys.stdin, master_fd], [], [])
    if sys.stdin in r:
        d = os.read(sys.stdin.fileno(), 10240)
        os.write(master_fd, d)
    elif master_fd in r:
        o = os.read(master_fd, 10240)
        if o:
            os.write(sys.stdout.fileno(), o)

# restore tty settings back
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
相关问题