我的目标是使用安装我的存储库和包的 python 脚本配置我的新 AWS 实例,然后使用子进程来配置(在本例中)postgres。从 yaml 或 json 文件中读取值。到目前为止,我已经成功安装了该环境的所有软件包和存储库。我被困的地方是一个 python 脚本,它将在 postgres 中创建一个用户,然后创建一个数据库。
import subprocess
# out is to show output, com is the stdin value(s) to pass
def run(command, out=False, com=False, ):
process = subprocess.Popen(
command,
close_fds=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
if out:
out = iter(process.stdout.readline, b'')
for line in out:
print(line)
if com:
process.stdin.write(com)
# http://stackoverflow.com/questions/16091112/python-pipe-to-popen-stdin
# process.communicate(com) doesn't fit, i need multiple stdin
run(['ls', '-l'], True) # works
run(['sudo', 'su', '-', 'postgres']) # works
run(['createuser'], False, 'testuser')
# broken, also after i get this working, this should be a list of stdin values
# this results in infinite lines:
# Shall the new role be a superuser? (y/n)
# I do have a workaround, run(['createuser', '-d', '-r', '-s', '-w', 'username'], False)
# Confirmed workaround created user successfully