0

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

5
  • 1
    Popen() instances are separate processes; you are not retaining the shell. Commented Sep 20, 2013 at 17:16
  • @MartijnPieters : how can I do that(retain shell)? Is it possible using subprocess or should I look for something else? Commented Sep 20, 2013 at 17:18
  • Why not run your Python script as root instead? sudo yourscript.py. Commented Sep 20, 2013 at 17:22
  • didn't help...same thing again Commented Sep 20, 2013 at 17:37
  • That was a separate question; the same remark, the session with psql doesn't carry over to a new command. A second Popen() instance runs a new program, it does not send commands to the old one. Use pexpect or write directly to the stdin of the first Popen() process. Commented Sep 20, 2013 at 17:55

1 Answer 1

1

When you create a new Popen() object, you start a new program. You are not communicating with an open psql shell.

You either have to drive psql directly by setting stdin to subprocess.PIPE, or, much easier, use pexpect to drive the psql shell:

import pexpect

psql = pexpect.spawn('psql')
psql.expect('=>')  # wait for the prompt
psql.send('create user user_name with password 'mypassword';')
# etc.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.