[英]Executing Interactive shell script in python
I have a shell script with ask for the user input. 我有一个shell脚本,要求用户输入。 Consider a below example
考虑下面的例子
Test.sh Test.sh
#!/bin/bash
echo -n "Enter name > "
read text
echo "You entered: $text"
echo -n "Enter age > "
read text
echo "You entered: $text"
echo -n "Enter location > "
read text
echo "You entered: $text"
Script Execution: 脚本执行:
sh test.sh
Enter name> abc
You entered: abc
Enter age > 35
You entered: 35
Enter location > prop
You entered: prop
Now i called this script in python program. 现在,我在python程序中调用了此脚本。 I am doing this using sub process module.
我正在使用子流程模块执行此操作。 As far as i know sub process module creates a new process.
据我所知,子流程模块创建了一个新流程。 The problem is when i execute the python script i am not able to pass the parameters to underlying shell script and the scipt is in hault stage.
问题是当我执行python脚本时,我无法将参数传递给底层的shell脚本,并且scipt处于故障状态。 Could some point me where i am doing wrong
可以指出我做错了什么
python script (CHECK.PY): python脚本(CHECK.PY):
import subprocess, shlex
cmd = "sh test.sh"
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()
print stdout
Python Execution: check.py Python执行:check.py
python check.py
Your code is working, but since you mention stdout=subprocess.PIPE
the content is going to stdout
variable you defined in stdout,stderr = proc.communicate()
. 您的代码正在运行,但是由于提到了
stdout=subprocess.PIPE
因此内容将转到您在stdout,stderr = proc.communicate()
定义的stdout
变量stdout,stderr = proc.communicate()
。 Remove stdout=subprocess.PIPE
argument from your Popen()
call and you will see the output. 从您的
Popen()
调用中删除stdout=subprocess.PIPE
参数,您将看到输出。
Alternatively, you should be using subprocess.check_call()
as: 另外,您应该将
subprocess.check_call()
用作:
subprocess.check_call(shlex.split(cmd))
Actually the subprocess does work - but you are not seeing the prompts because the standard out of the child process is being captured by proc.communicate()
. 实际上,子进程确实可以工作-但您看不到提示,因为子进程中的标准已由
proc.communicate()
捕获。 You can confirm this by entering values for the 3 prompts and you should finally see the prompts and your input echoed. 您可以通过输入3个提示的值来确认这一点,最后您应该会看到提示并回显了您的输入。
Just remove the stdout=subprocess.PIPE
(same for stderr) and the subprocess' stdout (stderr) will go to the terminal. 只需删除
stdout=subprocess.PIPE
(与stderr相同),然后子进程的stdout(stderr)将进入终端。
Or there are other functions that will start a subprocess and call communicate()
for you, such as subprocess.call()
or subprocess.check_call()
或者,还有其他函数将启动子进程并为您调用
communicate()
,例如subprocess.call()
或subprocess.check_call()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.