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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With