473,748 Members | 7,590 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

python + postgres psql + os.popen

hello, everyone.

i am trying to write a program which executes SQL commands stored in
..sql files.

i wrote a function called psql() whose contents look like the
following.

....
os.popen(comman d)
file = os.popen(comman d, 'w')
file.write(pass word)
file.close()
....

where command looks like
psql -h [host] -d [dbname] -U [username] -W -f "[filename]"

this works well. however, it does not show me any warning nor error
messages if there is one. for example, i am trying to create a table
which already exists in the database, it should show me a warning/error
message saying there already is one present in the database, or
something like that.

can anyone help me?

Jun 22 '06 #1
5 5914
damacy írta:
hello, everyone.

i am trying to write a program which executes SQL commands stored in
.sql files.

i wrote a function called psql() whose contents look like the
following.

...
os.popen(comman d)
file = os.popen(comman d, 'w')
file.write(pass word)
file.close()
...

where command looks like
psql -h [host] -d [dbname] -U [username] -W -f "[filename]"

this works well. however, it does not show me any warning nor error
messages if there is one. for example, i am trying to create a table
which already exists in the database, it should show me a warning/error
message saying there already is one present in the database, or
something like that.

can anyone help me?

You can put this in the beginning of your SQL file:

\set ON_ERROR_STOP

If you also want to know what command caused the error:

\set ECHO all

You can also use a library written for Python. For example, psycopg

http://initd.org/projects/psycopg1

Best,

Laszlo
Jun 22 '06 #2
damacy wrote:
hello, everyone.

i am trying to write a program which executes SQL commands stored in
.sql files.

i wrote a function called psql() whose contents look like the
following.

...
os.popen(comman d)
file = os.popen(comman d, 'w')
file.write(pass word)
file.close()
...

where command looks like
psql -h [host] -d [dbname] -U [username] -W -f "[filename]"

this works well.
But is a very strange way to access a RDBMS from Python code. Are you
aware of the existence of db modules ?
can anyone help me?


http://www.python.org/dev/peps/pep-0249/
http://initd.org/projects/psycopg1

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jun 22 '06 #3
damacy wrote:
hello, everyone. .... this works well. however, it does not show me any warning nor error
messages if there is one. for example, i am trying to create a table
which already exists in the database, it should show me a warning/error
message saying there already is one present in the database, or
something like that.

can anyone help me?


I recently needed to use psql from python on a computer that I couldn't
install psycopg on and I used something similar to this to do it (I
edited the code slightly to make it clearer):

from subprocess import Popen, PIPE

# Pass the password through an environment
# variable to prevent psql asking for it.
psql_env = dict(PGPASSWORD ='********')

# Create the subprocess.
proc = Popen(cmd, shell=True, env=psql_env, stdout=PIPE, stderr=PIPE)

# Try reading it's data.
data = proc.stdout.rea d()

# Check for errors.
err = proc.stderr.rea d()
if err: raise Exception(err)
It worked nicely for me, YMMV.
Hope that helps,

~Simon

Jun 22 '06 #4
hi, there. thanks for the help.

now i have a different problem now. i decided to use 'subprocess' and
'Popen' objects instead of 'os.popen()' function, which i believe do
not make much difference.

my code is like the following...

[1] link = subprocess.Pope n(command, stdin = subprocess.PIPE , stdout =
subprocess.PIPE , stderr = subprocess.PIPE , shell = True)
[2] link.communicat e(password)
[3] link.wait()
[4] err = link.communicat e()[1]
[5] if err != None: print str(err)

i have read several threads about 'subprocess' posted on this group and
still i have way too much confusion regarding the above section of
code.

1. i'm currently using MS Windows.
i remember some have said that communicate() function is not usable on
this OS.
could anyone confirm this?

2. i'm expecting an error message, as i am trying to create a table
which does already exist in the database.
but if i try to print out the error message as [5], it is just an EMPTY
string.
and, if i try the SAME THING using command-line, i get a correct error
message this time ('psql:createst udent.sql:12: ERROR: relation
"student" already exists').

HOWEVER, if i comment out [2] link.communicat e(password), meaning i do
not supply a password, it shows an error message, 'psql: fe_sendauth:
no password supplied', which is correct as expected.

my question is...
why does it work (i.e. showing a correct error message) when no
password supplied but NOT when creating a table which already exists in
the database? it should work for both cases.

thank you very much.
Simon Forman wrote:
damacy wrote:
hello, everyone.

...
this works well. however, it does not show me any warning nor error
messages if there is one. for example, i am trying to create a table
which already exists in the database, it should show me a warning/error
message saying there already is one present in the database, or
something like that.

can anyone help me?


I recently needed to use psql from python on a computer that I couldn't
install psycopg on and I used something similar to this to do it (I
edited the code slightly to make it clearer):

from subprocess import Popen, PIPE

# Pass the password through an environment
# variable to prevent psql asking for it.
psql_env = dict(PGPASSWORD ='********')

# Create the subprocess.
proc = Popen(cmd, shell=True, env=psql_env, stdout=PIPE, stderr=PIPE)

# Try reading it's data.
data = proc.stdout.rea d()

# Check for errors.
err = proc.stderr.rea d()
if err: raise Exception(err)
It worked nicely for me, YMMV.
Hope that helps,

~Simon


Jun 24 '06 #5
hi, there. thanks for the help.

now i have a different problem now. i decided to use 'subprocess' and
'Popen' objects instead of 'os.popen()' function, which i believe do
not make much difference.

my code is like the following...

[1] link = subprocess.Pope n(command, stdin = subprocess.PIPE , stdout =
subprocess.PIPE , stderr = subprocess.PIPE , shell = True)
[2] link.communicat e(password)
[3] link.wait()
[4] err = link.communicat e()[1]
[5] if err != None: print str(err)

i have read several threads about 'subprocess' posted on this group and
still i have way too much confusion regarding the above section of
code.

1. i'm currently using MS Windows.
i remember some have said that communicate() function is not usable on
this OS.
could anyone confirm this?

2. i'm expecting an error message, as i am trying to create a table
which does already exist in the database.
but if i try to print out the error message as [5], it is just an EMPTY
string.
and, if i try the SAME THING using command-line, i get a correct error
message this time ('psql:createst udent.sql:12: ERROR: relation
"student" already exists').

HOWEVER, if i comment out [2] link.communicat e(password), meaning i do
not supply a password, it shows an error message, 'psql: fe_sendauth:
no password supplied', which is correct as expected.

my question is...
why does it work (i.e. showing a correct error message) when no
password supplied but NOT when creating a table which already exists in
the database? it should work for both cases.

thank you very much.
Simon Forman wrote:
damacy wrote:
hello, everyone.

...
this works well. however, it does not show me any warning nor error
messages if there is one. for example, i am trying to create a table
which already exists in the database, it should show me a warning/error
message saying there already is one present in the database, or
something like that.

can anyone help me?


I recently needed to use psql from python on a computer that I couldn't
install psycopg on and I used something similar to this to do it (I
edited the code slightly to make it clearer):

from subprocess import Popen, PIPE

# Pass the password through an environment
# variable to prevent psql asking for it.
psql_env = dict(PGPASSWORD ='********')

# Create the subprocess.
proc = Popen(cmd, shell=True, env=psql_env, stdout=PIPE, stderr=PIPE)

# Try reading it's data.
data = proc.stdout.rea d()

# Check for errors.
err = proc.stderr.rea d()
if err: raise Exception(err)
It worked nicely for me, YMMV.
Hope that helps,

~Simon


Jun 24 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2946
by: Michael Lang | last post by:
Hi to all, can some one point me to the correct way, how to use PostgreSQLs "COPY" feature from within python ? What i want to do is: connect start transaction drop current tablecontens
2
4545
by: Xah Lee | last post by:
Python Doc Problem Example: os.system Xah Lee, 2005-09 today i'm trying to use Python to call shell commands. e.g. in Perl something like output=qx(ls) in Python i quickly located the the function due to its
48
11914
by: Edwin Quijada | last post by:
Hi !! Everybody I am developing app using Delphi and I have a question: I have to save pictures into my database. Each picture has 20 o 30k aprox. What is the way more optimus? That 's table will have 500000 records around. Somebody said the best way to do that was encoder the picture to field bytea but I dont know about this. Another way is save the path to the picture file but I dont like so much because I need to write to disk by OS...
0
1219
by: phil campaigne | last post by:
scott.marlowe wrote: > On Thu, 4 Mar 2004, phil campaigne wrote: > > > >> Hello, >> when I login to linux and check the env's I see: >> PATH=/usr/local/pgsql/bin:/bin:/usr/bin:/usr/local/bin:/usr/bin/X11:/usr/X11R6/bin:/home/postgres/bin:/opt/IBMJava2-14/bin:/opt/IBMJava2-14/jre/bin:/usr/local/pgsql/bin >>
6
2954
by: Prabu Subroto | last post by:
Dear my friends... Usually I use MySQL. Now I have to migrate my database from MySQL to Postgres. I have created a database successfully with "creatdb" and a user account successfully. But I can not access the postgres with pgaccess.
0
1739
by: Együd Csaba | last post by:
> -----Original Message----- > From: pgsql-admin-owner@postgresql.org > On Behalf Of Együd Csaba > Sent: 2004. július 16. 12:23 > To: pgsql-admin (E-mail) > Subject: URGENT - Postgres won't work > > > Hi All, > I have the following problem: (RH7.1, PostgreSQL 7.4.1)
3
1811
by: Darkcamel | last post by:
Hello all, I am new to postgres and don't really understand how the database is set-up. I am very fluent with mysql and sql2000, but postgres is new to me. If anyone can point me to some good links I would appreciate it very much. Thanks, Darkcamel
7
2190
by: damacy | last post by:
hi, there. i have this question which might sound quite stupid to some people, but here we go anyway. i have written a python program which interacts with a postgresql database. what it does is simply drops an existing database called 'mytempdb'. the code looks like below; link = subprocess.Popen(command, stdin = subprocess.PIPE, stdout =
0
2740
by: kishoramballi | last post by:
Hi, I have created table using following sql statement through psql tool in test database using create table t1(f1 int); table is created. Now I am using an odbc script to insert 5 records. But it inserts 6 records NULL value being the first one inserted. the code snippet is as below. ... ...
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9325
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8244
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.