0

I want to subprocess.popen() a Swift program with Python 3.

parent.py:

import subprocess

#p = subprocess.Popen(['python3', 'sub.py'], universal_newlines = True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=1)

p = subprocess.Popen(['swift', 'sub.swift'], universal_newlines = True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=1)

while True:
    a=input('command:')
    if not a:
        print(p.stdout.readline())
    else:
        p.stdin.write(a+'\n')

sub.swift

while true {
    print(readLine()!)
}

It doesn't work. p.stdout.readline() stalls.

If I change the command to ['python3', 'sub.py'] and have

sub.py

while True:
    print(input())

It works:

> python3 parent.py
command:a
command:[enter]
a

command:asdf
command:[enter]
asdf

Why is this? How can I solve it?

John Hao
  • 3
  • 2

1 Answers1

0

Flushing standard output worked for me:

import Darwin
while true {
    print(readLine()!)
    fflush(stdout)
}

I'm not too familiar with Python, but my guess is that the Python print probably automatically flushes.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thank you! That helped a lot. Can you please elaborate on flushing? Is the program not writing to stdout directly? – John Hao May 10 '22 at 09:18
  • @JohnHao Correct, stdout is buffered in this particular case (I don't know how big the buffer is), since your python program isn't able to read anything without flushing. See also: https://stackoverflow.com/questions/3723795/is-stdout-line-buffered-unbuffered-or-indeterminate-by-default – Sweeper May 10 '22 at 11:09