Python os.system() 输入文本到脚本

标签 python bash os.system

我有一个需要自动化的脚本,所以它是一个 .sh我想在 python 脚本中运行的脚本:像这样:

import os
os.system('./script.sh -p 1234')

脚本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

如何让 python 脚本输入/插入/传递这 3 个需要的值到 script.sh .

最佳答案

您可以使用 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')

关于Python os.system() 输入文本到脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346707/

相关文章:

python - 如何在某些条件下用平均值限制 pandas 列

python - 如何查看请求通过线路发送的实际数据?

python - 外语 Chatterbot 网络应用程序

bash - shell脚本中的异常处理?

python - python中类继承Generic的目的是什么?

linux - 使用分隔符拆分日志文件以保持数据完整性

windows - 在 Windows 上的 Bash 上说错误

python - 在 python linux 中执行命令时在 python 中给出响应 os.system()

python - 将 Os.system 结果存储在变量中