0
我的目標是使用一個python腳本來配置我的新AWS實例,該腳本安裝我的存儲庫和包,然後利用子進程配置(本例中爲)postgres。值是從yaml或json文件中讀取的。到目前爲止,我已經成功安裝了環境的所有軟件包和回收站。我被卡住的地方是一個python腳本,它將在postgres中創建一個用戶,然後創建一個數據庫。將subprocess.popen與多個stdin配合使用來配置系統:Python 2.7
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
它得到運行。看到以下的無限輸出:新角色應該成爲超級用戶嗎? (y/n) –
所以解決這個問題的最好方法是不要運行需要多個stdin的子進程的命令。不過,我有一種感覺,這在Python 3中起作用。 –
由此完成:https://github.com/muhuk/cuisine-postgresql/blob/master/cuisine_postgresql.py –