Search code examples
pythonpostgresqlpsql

How could call a psql command from Python script


I'm trying to create database table with psql command called from python scrip but I got the following error: [Errno 2] No such file or directory: b'psql -d postgres -U postgres -h postgres -W -c "CREATE DATABASE db_316c76d0 OWNER user_316c76d0;"'

The script is:

try:
  create_user_sh = f'psql -d {settings.DB_NAME} -U {settings.DB_USER} -h {settings.DB_HOST} -W -c "CREATE DATABASE {name} OWNER {user};"'.encode()
  proc = Popen(create_user_sh, stdin=PIPE, stdout=PIPE)
  proc.communicate(settings.DB_PASSWORD.encode())
except Exception as ex:
  print(str(ex))

Any idea how to solve it ?


Solution

  • Pass a sequence of arguments to Popen:

      create_user_sh = ('psql', '-d', settings.DB_NAME, '-U', settings.DB_USER, '-h', settings.DB_HOST, '-W', '-c', f'CREATE DATABASE {name} OWNER {user};')