如何在Python中运行Golang可执行文件/与之交互?

2024-04-28 08:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows上有一个名为cnki-downloader.exe的命令行Golang可执行文件(在这里开源:https://github.com/amyhaber/cnki-downloader)。我想在Python中运行这个可执行文件,并与之交互(获取其输出,然后输入内容,然后获取输出,等等)

这是一个命令行程序,所以我认为它和MSVC构建的普通Windows命令行程序是一样的。我的代码是这样的:

# coding=gbk

from subprocess import Popen, PIPE

p = Popen(["cnki-downloader.exe"], stdin=PIPE, stdout=PIPE)
#p = Popen(["WlanHelper.exe"], stdin=PIPE, stdout=PIPE )

p.stdin.write( 'XXXXXX\n' )
result1 = p.stdout.read() # <---- we never return here
print result1

p.stdin.write( '1\n' )
result2 = p.stdout.read()
print result2

我的Python代码在使用cnki-downloader.exe参数的Popen调用处停止。然后我尝试了一个由MSVC构建的C命令行程序(名为WlanHelper.exe),它运行良好。我的脚本可以从exe获取输出。在

<> P> Golang的可执行文件的命令行机制与本地C/C++程序不同,其他语言(如Python)调用和交互很难。在

所以我想知道如何在Windows上用Python等其他语言与Golang可执行文件交互?。如果这是不可能的,我也可以考虑修改Golang程序的源代码(因为它是开源的)。但我希望我不会走那一步。谢谢!在


注意:

如果可能,我希望直接调用这个Golang可执行文件,而不是将其修改到库中并让Python导入它。如果我必须将Golang修改成一个库,为什么不干脆去掉交互方式,把所有的东西都变成命令行参数呢?没有必要费心去写一个果郎图书馆。所以请假设Golang程序是封闭源代码的。我不认为Python无法调用命令行Golang程序。如果是这样,那么我认为Golang真的在与其他语言的互操作性方面需要改进。在


Tags: 命令行程序语言可执行文件windowsstdinstdoutdownloader
1条回答
网友
1楼 · 发布于 2024-04-28 08:21:47

查看您正在使用的子进程模块的documentation,它们似乎有关于使用stdout.read()和朋友的死锁的警告:

Warning This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.

所以,也许可以试着用communicate代替?在

相关问题 更多 >