[codesyntax lang=”python”]
import subprocess
def uci():
# 引擎
command = ['./uci']
# 使用Popen启动控制台程序,同时将stdin, stdout, stderr设置为PIPE
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
# 初始化输出信息
all_output = ""
# 发送初始输入给控制台程序
initial_input = "some initial input\n"
process.stdin.write(initial_input)
process.stdin.flush()
# 持续读取输出直到没有更多输出
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
all_output += output
# 可以继续发送更多输入,例如:
more_input = "more input\n"
process.stdin.write(more_input)
process.stdin.flush()
# 再次持续读取输出
while True:
more_output = process.stdout.readline()
if more_output == '' and process.poll() is not None:
break
if more_output:
all_output += more_output
finally:
# 完成交互后,关闭stdin,以通知控制台程序输入结束
process.stdin.close()
# 等待控制台程序结束
process.wait()
# 返回所有输出信息
return all_output
# 调用引擎函数并打印返回的输出信息
output = uci()
print("引擎全部输出信息:")
print(output)
[/codesyntax]