Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a python script that can communicate with the input and output of a swift executable?

So, I have a simple swift program, a one file, main.swift program, that looks like this.

import Foundation

var past = [String]()

while true {
    let input = readLine()!
    if input == "close" {
        break
    }
    else {
        past.append(input)
        print(past)
    }
}

I want to write a python script that can send an input string to this program, and then return the output of that, and have it be run over time. I can't use command line arguments as I need to keep the swift executable running over time.

I have tried os.system() and subprocess.call() but it always gets stuck because neither of them give input to the swift program, but they do start the executable. My shell gets stuck basically waiting for my input, without getting input from my python program.

This is my last python script i attempted:

import subprocess

subprocess.call("./Recommender", shell=True)
f = subprocess.call("foo", shell=True)
subprocess.call("close", shell=True)

print(f)

any ideas on how to do this correctly?

EDIT:

So now I have this solution

import subprocess
print(True)
channel = subprocess.Popen("./Recommender", shell = False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(True)
channel.stdin.write(("foo").encode())
channel.stdin.flush()
print(True)
f = channel.stdout.readline()

channel.terminate()
print(f)
print(True)

However, it stops at reading the line from stdout any ideas how to fix this?

like image 965
Josh Weinstein Avatar asked Nov 08 '22 14:11

Josh Weinstein


1 Answers

I think the following code is what you're looking for. It uses a pipe so you can programmically send data without using command line arguments.

process = subprocess.Popen("./Recommender", shell=True, stdin=subprocess.PIPE)
process.stdin.write(('close').encode())
process.stdin.flush()
like image 115
ritlew Avatar answered Nov 14 '22 22:11

ritlew