所以,我有一个简单的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()
原文地址:https://codeday.me/bug/20190706/1395219.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。