Python';s sh模块-脚本是否可以请求输入?
使用Python的Python';s sh模块-脚本是否可以请求输入?,python,sh,Python,Sh,使用Python的sh,我正在运行请求输入的第三方shell脚本(这并不重要,但准确地说,我正在运行带有--step选项的Ansible2剧本) 作为对正在发生的事情的过分简化,我构建了一个请求输入的简单bash脚本。我相信,如果让这个简单的例子起作用,我也可以让原来的案例起作用 请考虑这个BASH脚本Hello .SH: #!/bin/bash echo "Please input your name and press Enter:" read name echo "Hello $name
sh
,我正在运行请求输入的第三方shell脚本(这并不重要,但准确地说,我正在运行带有--step
选项的Ansible2剧本)
作为对正在发生的事情的过分简化,我构建了一个请求输入的简单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)
我怎样才能做到这一点呢?有两种方法可以解决这个问题:
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)
#!/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
您可以使用
子流程
,这非常简单。在sh
中,您可以传递命令行args,这样您也可以修改脚本以获取args?我已经更新了我的问题,提供了更多详细信息,因此,为了更好地解释真正的问题,方法中的\u应该仍然有效是吗?@GaneshK我需要一种动态的交互方式来输入。请看我的答案。