Home > database >  Subprocess.popen() Doesn't Work With Swift
Subprocess.popen() Doesn't Work With Swift

Time:05-10

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?

CodePudding user response:

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.

  • Related