def psql_csv_run(sql_command, error_handler=None):
 csv_query = 'COPY ({query}) TO STDOUT WITH CSV HEADER;'.format(query=sql_command)
 new_env = os.environ.copy()
 new_env.setdefault('PGOPTIONS', '')
 new_env['PGOPTIONS'] += ' --statement-timeout=0'
 psql_proc = popen_nonblock([PSQL_BIN, '-d', 'postgres', '--no-password', '--no-psqlrc', '-c', csv_query], stdout=PIPE, env=new_env)
 stdout = psql_proc.communicate()[0].decode('utf-8')
 if (psql_proc.returncode != 0):
  if (error_handler is not None):
   error_handler(psql_proc)
  else:
   assert (error_handler is None)
   raise UserException('could not csv-execute a query successfully via psql', 'Query was "{query}".'.format(sql_command), 'You may have to set some libpq environment variables if you are sure the server is running.')
 assert (psql_proc.returncode == 0)
 return csv.reader(iter(stdout.strip().split('\n')))

def psql_csv_run ( sql_command , error_handler = None ) : csv_query = 'COPY ({query}) TO STDOUT WITH CSV HEADER;' . format ( query = sql_command ) new_env = os . environ . copy ( ) new_env . setdefault ( 'PGOPTIONS' , '' ) new_env [ 'PGOPTIONS' ] += ' --statement-timeout=0' psql_proc = popen_nonblock ( [ PSQL_BIN , '-d' , 'postgres' , '--no-password' , '--no-psqlrc' , '-c' , csv_query ] , stdout = PIPE , env = new_env ) stdout = psql_proc . communicate ( ) [ 0 ] . decode ( 'utf-8' ) if ( psql_proc . returncode != 0 ) : if ( error_handler is not None ) : error_handler ( psql_proc ) else : assert ( error_handler is None ) raise UserException ( 'could not csv-execute a query successfully via psql' , 'Query was "{query}".' . format ( sql_command ) , 'You may have to set some libpq environment variables if you are sure the server is running.' ) assert ( psql_proc . returncode == 0 ) return csv . reader ( iter ( stdout . strip ( ) . split ( '\n' ) ) )
runs psql and returns a csvreader object from the query this csvreader includes header names as the first record in all situations .