Question

When running a copy command via psycopg2 I get the error

psycopg2.ProgrammingError: could not open file "/tmp/<>.txt" for writing: Permission denied

I don't know the etiology of the issue, but in the past I have been able to run copy commands without this problem. Unlike the answer to this question, changing the output location to home folder doesn't change the result. I've tried resetting the /tmp permissions with chmod -R 777 /tmp, but with no success. Running the script with sudo permissions hasn't worked either. What should I try next to troubleshoot this issue?

A code sample for the procedure is:

import psycopg2 as post
con = post.connect(<dbname>, <host>, <user>, <password>)
cur = con.cursor()
with open('/tmp/out_path.txt', 'w') as f:
    cur.copy_expert("COPY <table> TO '/tmp/out_path.txt' WITH CSV HEADER" + 
                    "DELIMITER AS E'\t'", f)
# close connections, etc

I'm on Ubuntu 12.04 server, PostgreSQL 9.3, Python 2.7. Both the client and the host are on the same machine - I'm running the script while logged in via ssh.

Était-ce utile?

La solution

with open('/tmp/out_path.txt', 'w') as f:
    cur.copy_expert("""
        COPY <table> TO STDOUT WITH CSV HEADER DELIMITER AS E'\t'
    """, f)

From the docs:

The sql statement should be in the form COPY table TO STDOUT to export table to the file object passed as argument

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top