Python的sh模块是否有可能让脚本请求输入?

2024-09-24 00:35:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

所以请考虑这个bash脚本你好.sh公司名称:

#!/bin/bash

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

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

^{pr2}$

我该怎么做?在


Tags: nameecho脚本bash选项stepsh公司
2条回答

在遵循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)

例如,输出为:

^{pr2}$

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

  1. 在中使用\u:

在中使用_,我们可以传递一个可以作为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. 如果您愿意修改脚本,请使用命令行参数。在

相关问题 更多 >