繁体   English   中英

如何编写一个可以与swift可执行文件的输入和输出进行通信的python脚本?

[英]How to write a python script that can communicate with the input and output of a swift executable?

所以,我有一个简单的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()但它总是被卡住,因为他们都没有给输入快捷程序,但他们启动可执行文件。 我的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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM