Use the psycopg.Binary() function to escape the binary data:
>>> db = psycopg.connect("dbname=%s user=%s" % (database, user))
>>> db.autocommit(True)
>>> cursor = db.cursor()
>>> file = "/path/to/binary_file.jpg"
>>> fd = open(file, "r")
>>> contents = fd.read(os.stat(file)[6])
>>> fd.close()
>>> cursor.execute("INSERT INTO pr0n (image) VALUES (%s)", (psycopg.Binary(contents)))
binarybyteacursordbapiescapeinteractivelanguagespostgresqlprogrammingpsycopgpython
Set this variable in your ~/.psqlrc to stop on error when psql is used to run non-interactive scripts (e.g. cat file | psql ...):
\set ON_ERROR_STOP 1
Or use it from the command line:
$ psql ... -v ON_ERROR_STOP=1 ...
commandsconfigurationdebugginginteractivepipepostgresqlpsqlpsqlrc