elleciel
elleciel

Reputation: 2567

Python/PostgreSQL - check if server is running

I've just started using the psycopg2 module to access a local PostgreSQL server and I'll like a way to progammatically check if the server is already started so my program can handle the error when I try to start the server:

psqldir = 'C:/Program Files/PostgreSQL/9.2/bin'    # Windows
username = os.environ.get('USERNAME')
dbname = 'mydb'
os.chdir(psqldir)
os.system('pg_ctl start -D C:/mydatadir')   # Error here if server already started
conn = psycopg2.connect('dbname=' + dbname + ' user=' + username)
cur = conn.cursor()

I experimented a little and it seems that this returns a "0" or "3", which would solve my problem, but I didn't find any information on the PostgreSQL/psycopg2 manual that confirms if this is a documented behavior:

server_state = os.system('pg_ctl status -D C:/mydatadir')

What's the best way? Thanks!

Upvotes: 3

Views: 7652

Answers (2)

Orlov Const
Orlov Const

Reputation: 371

Try to use pgrep command.

proc = subprocess.Popen(["pgrep -u postgres -f -- -D"], stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    try:
        if int(out) > 0:
            return True
    except Exception as e:
        return False

Upvotes: 1

Craig Ringer
Craig Ringer

Reputation: 324511

From the pg_ctl documentation:

-w

Wait for the startup or shutdown to complete. Waiting is the default option for shutdowns, but not startups. When waiting for startup, pg_ctl repeatedly attempts to connect to the server. When waiting for shutdown, pg_ctl waits for the server to remove its PID file. pg_ctl returns an exit code based on the success of the startup or shutdown.

You will also find pg_ctl status useful:

status mode checks whether a server is running in the specified data directory. If it is, the PID and the command line options that were used to invoke it are displayed. If the server is not running, the process returns an exit status of 3.

Upvotes: 5

Related Questions