Python sh 模块 - 脚本是否可以请求输入?

标签 python sh

使用 Python 的 sh,我正在运行请求我输入的第 3 方 shell 脚本(并不是说它很重要,但准确地说,我正在使用 - 运行 Ansible2 playbook) -step 选项)

作为对正在发生的事情的过度简化,我构建了一个请求输入的简单 bash 脚本。我相信,如果使这个简单的示例起作用,我也可以使原始案例起作用。

所以请考虑这个 bash 脚本 hello.sh:

#!/bin/bash

echo "Please input your name and press Enter:"
read name
echo "Hello $name"

我可以使用 sh 模块从 python 运行它,但它无法接收我的输入...

import errno
import sh

cmd = sh.Command('./hello.sh')

for line in cmd(_iter=True, _iter_noblock=True):
    if line == errno.EWOULDBLOCK:
        pass
    else:
        print(line)

我怎样才能做到这一点?

最佳答案

关注 this tutorial 后,这适用于我的用例:

#!/usr/bin/env python3

import errno
import sh
import sys


def sh_interact(char, stdin):
    global aggregated
    sys.stdout.write(char)
    sys.stdout.flush()
    aggregated += char
    if aggregated.endswith(":"):
        val = input()
        stdin.put(val + "\n")


cmd = sh.Command('./hello.sh')
aggregated = ""

cmd(_out=sh_interact, _out_bufsize=0)

例如,输出为:

$ ./testinput.py
Please input your name and press Enter:arod

Hello arod

关于Python sh 模块 - 脚本是否可以请求输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50430328/

相关文章:

python - 虚拟数据包字段 : how to handle a polymorphic protocole?

linux - 将文件夹中的所有文件名传递给 bash 脚本,添加特殊附录

bash - 如何使用 shell 脚本从每行查找负数并仅打印一次

shell - 检测脚本是否源自 "/bin/sh"

linux - sh shell 中数组中的命令输出

巴特利特周期图的 Python 实现

python - 缩小 Matplotlib

python - 一个类的值(value)是什么?

python - Pandas 检查两列是否相同

linux - 在文件中的变量完全匹配后打印第二列值