使用 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/