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!
subprocess
is certainly the right way to go, but I strongly disagree with the other part of your advice. It is generally not wise to parse for strings in output; ephedyn is taking the correct approach by testing return values. String parsing bites you badly the first time someone whose computer is configured for Russian or Thai or ... tries to run your program and the strings don't match anymore. Or someone makes a typo fix or wording clarification in an updated version. It's a bad practice that should be a last resort. – Craig Ringer Apr 20 '13 at 10:05