所以,我有一个简单的
swift程序,一个文件,main.swift程序,看起来像这样.
import Foundation
var past = [String]()
while true {
let input = readLine()!
if input == "close" {
break
}
else {
past.append(input)
print(past)
}
}
我想编写一个python脚本,可以将输入字符串发送到此程序,然后返回该输出,并让它随着时间的推移运行.我不能使用命令行参数,因为我需要保持swift可执行文件随时间运行.
我已经尝试过os.system()和subprocess.call()但它总是卡住,因为它们都没有给swift程序提供输入,但它们确实启动了可执行文件.我的shell基本上等待我的输入卡住了,没有从我的python程序获得输入.
这是我尝试的最后一个python脚本:
import subprocess
subprocess.call("./Recommender", shell=True)
f = subprocess.call("foo", shell=True)
subprocess.call("close", shell=True)
print(f)
有关如何正确执行此操作的任何想法?
编辑:
所以现在我有了这个解决方案
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)
但是,它停止从stdout读取任何想法如何解决这个问题?
最佳答案 我认为以下代码是您正在寻找的.它使用管道,因此您可以在不使用命令行参数的情况下以编程方式发送数据.
process = subprocess.Popen("./Recommender", shell=True, stdin=subprocess.PIPE)
process.stdin.write(('close').encode())
process.stdin.flush()