0
        text="odoo15"
        message=text.encode()
        

        proc = Popen(["psql",
        "-h","localhost",
        "-d", "database", 
        "-U", "User", 
        "-f", "/path/dump.sql"], stdin=PIPE)

        proc.communicate(input=message)

Before I execute that code I am connected with the database using psycopg. I want to execute sql code from a file onto a database to create tables and fill them with data coming from the dumb file. The trouble I have is that I still need to manually enter the password in the console for this code to work. I do not understand why it is not taking the password from proc.communicate. I would be really grateful for some help.

I also tried it with subprocess.run and having input as an argument but had the same problem. My first idea was to use the /i command from psql but since I cannot execute psql in psycopg it did not work. I also tried: cursor.execute(open("/path/dump.sql", "r").read()) and os.system("sudo -u user psql database < /path/dump.sql") but the first could not execute because i have \ in my file and the second did also not work.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • Does this answer your question? [How do I specify a password to 'psql' non-interactively?](https://stackoverflow.com/questions/6405127/how-do-i-specify-a-password-to-psql-non-interactively) – Maurice Meyer Aug 24 '22 at 09:38

1 Answers1

0

If you want to avoid all of this, you can directly set the PGPASSWORD env var. When doing this, the CLI won't ask for the password.

You can do this in multiple ways:

  1. export PGPASSWORD=yourpassword
  2. proc = Popen(["PGPASSWORD=yourpassword", "psql",...
  3. PGPASSWORD=yourpassword python yourscript.py
  4. Inside your python script, import os; os.environ["PGPASSWORD"] = "yourpassword"
  5. Modify the env var for the subprocess only
RobinFrcd
  • 4,439
  • 4
  • 25
  • 49