【问题标题】:Interactive, non-blocking subprocess.Popen script without using communicate or pexpect交互式、非阻塞 subprocess.Popen 脚本,不使用通信或 pexpect
【发布时间】:2015-11-12 03:23:01
【问题描述】:

A:为什么会阻塞?

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 ...

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

【问题讨论】:

  • 您可以用check_output(['ls', '-lashtr']) 替换的示例代码与问题不对应(对于文本中描述的问题来说太简单了,没有意义)。使用subprocess 与子进程进行基于对话的交互并不容易。在一般情况下忘记“稍微”。问题的文本(不是代码)太宽泛了:"splits out the errors" (do you want to capture stdout/stderr separately?) 是什么意思。你如何找到几个命令的输出之间的界限?什么是重跑?
  • 我想要一个打开的进程并让它保持打开状态。沟通无法帮助我解决这个问题,因为它关闭了流程。如果您需要更多信息,请考虑以下内容: docker run -i -t ubuntu /bin/bash; su - ;运行脚本;检查输出;
  • 不要告诉我们你认为什么是行不通的:(1) 你可能是错的,例如,你可以使用.communicate() 运行多个命令 (2) 它没有告诉我们你的实际问题是。回答我之前评论中的问题。
  • 我不确定我是否可以更清楚:我想要一个持久的 shell,我可以在其中通过网络运行任意 shell 命令,特别是因为我正在处理 docker 容器。我想要一个简单的例子来解释这个问题。如果您有更好的解释方式,我很乐意进行编辑。通信关闭文件描述符。
  • 我没有看到我提出的问题的答案。帮助别人帮助你是你的责任。

标签: python subprocess popen


【解决方案1】:

A:为什么会阻塞?

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

B:我怎样才能稍微按摩一下(强调轻微),这样它才能运行而不会阻塞?

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

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

【讨论】:

  • 我想保持外壳打开。
【解决方案2】:

这是我的另一个答案的示例: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)

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 2019-10-30
    • 2020-08-17
    • 2023-03-04
    • 2018-01-27
    • 1970-01-01
    • 2017-06-23
    • 2021-06-08
    • 2014-04-04
    相关资源
    最近更新 更多