I want to execute a python script which executes the following command in order:
sudo su - postgres #change user to postgres
psql #enter the psql command promt from
create user user_name with password 'mypassword'; #
create database voylla_development with encoding = 'utf8'; #all the 3 commands are to be executed in psql command prompt
grant all on database voylla_development to user_name; #
exit #psql prompt
exit #postgres user
cat <backup_file_name> | zcat - | PGPASSWORD=mypassword psql -d voylla_development -h localhost -p 5432 -U user_name
I tried using subprocess and os.system():
cmd='sudo -u postgres psql'
args = shlex.split(cmd)
p=subprocess.Popen(args)
p.wait()
cmd1='psql'
args1 = shlex.split(cmd1)
p=subprocess.Popen(args1)
p.wait()
##and so on for each command
But the script stops after I login as postgres user. How can I continue the script after user change? Thanks
EDIT: using psycopg2 helped the cause
Popen()instances are separate processes; you are not retaining the shell.sudo yourscript.py.psqldoesn't carry over to a new command. A secondPopen()instance runs a new program, it does not send commands to the old one. Usepexpector write directly to thestdinof the firstPopen()process.