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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:19:59  来源:igfitidea点击:

Python os.system() input text to script

pythonbashos.system

提问by PepperoniPizza

I have a script that I need to automate, so it's a .shscript 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.shneeds 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.Popento start the script and the communicatemethod 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')