code: def pgexport(
      database_uri,
      table_name,
      filename,
      encoding="utf-8",
      dialect=csv.excel,
      callback=None,
      timeout=0.1,
      chunk_size=8388608,
  ):
      
  
      if isinstance(dialect, six.text_type):
          dialect = csv.get_dialect(dialect)
  
      # Prepare the `psql` command to be executed to export data
      command = get_psql_copy_command(
          database_uri=database_uri,
          direction="TO",
          encoding=encoding,
          header=None,  # Needed when direction = 'TO'
          table_name=table_name,
          dialect=dialect,
      )
      fobj = open_compressed(filename, mode="wb")
      try:
          process = subprocess.Popen(
              shlex.split(command),
              stdin=subprocess.PIPE,
              stdout=subprocess.PIPE,
              stderr=subprocess.PIPE,
          )
          total_written = 0
          data = process.stdout.read(chunk_size)
          while data != b"":
              written = fobj.write(data)
              total_written += written
              if callback:
                  callback(written, total_written)
              data = process.stdout.read(chunk_size)
          stdout, stderr = process.communicate()
          if stderr != b"":
              raise RuntimeError(stderr.decode("utf-8"))
  
      except FileNotFoundError:
          raise RuntimeError("Command `psql` not found")
  
      except BrokenPipeError:
          raise RuntimeError(process.stderr.read().decode("utf-8"))
  
      return {"bytes_written": total_written}
docs: Export data from PostgreSQL into a CSV file using the fastest method
  
      Required: psql command