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

时间:2018-05-19 23:21:55

标签: python sh

使用Python sh,我正在运行请求输入的第三方shell脚本(并不重要,但确切地说,我正在使用{运行Ansible2手册) {1}}选项)

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

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

--step

我可以使用#!/bin/bash echo "Please input your name and press Enter:" read name echo "Hello $name" 模块从python运行它,但它无法接收我的输入......

sh

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

关注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

答案 1 :(得分:0)

有两种方法可以解决这个问题:

  1. 使用_in:
  2. 使用_in,我们可以传递一个列表,该列表可以作为python脚本中的输入

    cmd = sh.Command('./read.sh')
    stdin = ['hello']
    for line in cmd(_iter=True, _iter_noblock=True, _in=stdin):
        if line == errno.EWOULDBLOCK:
            pass
        else:
            print(line)
    
    1. 如果您愿意修改脚本,请使用命令行参数。