简体   繁体   中英

Subprocess.popen() Doesn't Work With Swift

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM