5

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?

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

7 Comments

how do i get the stdout of the pipe?
You want the program to talk back to the python code?
when i used os.system(), it would always return what was the result printed to the console, for example, but i want this to go on for a continuous process.
I'm not familiar with swift, how do I get Recommender?
its a custom executable i wrote. Your solution however does work, just needs a little tweaking.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.