0

For example, lets say I want to access a Postgresql database in the shell and apply the command select *;. This would require me to run:

  1. psql -U postgres
  2. <insert the password> (optional)
  3. select *;

and ideally get the the intermediate output after each step. This is only a toy example, for doing this sqlalchemy would be a good pick, but still it should be possible through pythons subprocess module.

What I have tried based on this post:

    start = f"psql -U postgres"
    fw = open("tmpout.txt", "wb")
    fr = open("tmpout.txt", "r")
    p = subprocess.Popen(start, stdin=subprocess.PIPE, stdout=fw, stderr=fw, bufsize=1, 
        shell=True)
    p.stdin.write(bytes("select *;", 'utf-8'))
    out = fr.read() # Here i would expect the result of the select, but it doesn't terminate..
LC117
  • 426
  • 4
  • 12
  • The Python `pexpect` module might be an easier way to be interactive with other processes... https://pexpect.readthedocs.io/en/stable/ – Mark Setchell Apr 22 '21 at 08:19
  • It doesn't terminate because subprocess doesn't terminate. You should read it line by line look at https://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line – lojza Apr 22 '21 at 09:16

0 Answers0