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