bash Python os.system() 输入文本到脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23346707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python os.system() input text to script
提问by PepperoniPizza
I have a script that I need to automate, so it's a .sh
script which I want to run inside a python script: something like this:
我有一个需要自动化的.sh
脚本,所以它是一个我想在 python 脚本中运行的脚本:像这样:
import os
os.system('./script.sh -p 1234')
The script script.sh
needs the user to input 3 fields, 1) the sudo password, 2) a string and 3) a string.
该脚本script.sh
需要用户输入 3 个字段,1)sudo 密码,2)一个字符串和 3)一个字符串。
Enter password for user: xxxx #typed by me
Enter Auth Username: xxxx #typed by me
Enter Auth Password: xxx #typed by me
How can I make the python script to type/insert/pass those 3 needed values to script.sh
.
我怎样才能让 python 脚本输入/插入/传递这 3 个需要的值到script.sh
.
回答by larsks
You can use subprocess.Popen
to start the script and the communicate
method to pass it input. Something like this:
您可以使用subprocess.Popen
启动脚本和communicate
传递输入的方法。像这样的东西:
import subprocess
p = subprocess.Popen(['./script.sh', '-p', '1234'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate(input='password\nauth username\nauth password\n')