title: Python/PostgreSQL - check if server is running
body: <p>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:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>server_state = os.system('pg_ctl status -D C:/mydatadir')
  </code></pre>
  
  <p>What's the best way? Thanks!</p>