c++ - 通过 CGI python 脚本在服务器端运行 .exe 文件

标签 c++ python html cgi exe

我有一个带有一个按钮的 html 文件。单击按钮时,将调用 javascript 函数“run”:

function run() {
            window.open("http://localhost/cgi-bin/run.py", "_self");
        }

run.py 只是尝试运行一个 helloworld.exe 程序,该程序在终端中输出字符串“helloworld”,但什么也没有发生,浏览器会无限期地“等待本地主机”。

#!python
import sys, string, os, cgitb

cgitb.enable()
os.system("helloworld.exe")

我单独尝试过 helloworld.exe 并且它有效,我在终端上运行 run.py,它有效,我还在浏览器上测试了测试站点 http://localhost/cgi- bin/helloworld.py,它工作正常(helloworld.py 是另一个脚本,只是为了查看我的 apache 配置是否正确)。

我正在使用 wamp。

我想做的是一个更大的程序,它允许客户端连接到服务器,并与服务器端的程序“交互”。程序已经用c++完成,不会翻译成php或javascript。

编辑:我一直在尝试使用函数:subprocess.Popen、subprocess.call 和 os.system。我还测试了运行我创建的 .exe 文件的代码,这些文件位于 apache/cgi-bin 文件夹中,或者像写字板这样的可执行文件,位于 c:\windows 中。当 python 脚本从终端运行时它总是成功,而当从浏览器尝试时它永远不会工作。有没有可能是因为我使用的服务器?我使用 wamp 的 apache,并在 httpd.conf 文件中添加了“AddHandler cgi-script .exe”这句话。

最佳答案

我确信它在本地不起作用。 os.system 返回命令的退出代码,而不是它的输出。

您将需要使用 subprocess.Popen 和管道输出以读取输出。

import subprocess
p = subprocess.Popen("whatever.exe",stdout=subprocess.PIPE)
print p.stdout.read()
p.wait()

此外,您的 CGI 脚本的输出不是有效的 HTTP 协议(protocol),这取决于您的服务器,这可能会导致问题(一些服务器会清理脚本的输出,而另一些服务器则希望它们被正确编写)。

对我而言,此代码示例有效(在 GNU/Linux 上使用 weborf 作为服务器,但它应该是相同的)。您可以尝试设置内容类型并发送\r\n\r\n 最终序列。服务器不应发送它,因为 CGI 脚本可能想要添加更多 HTTP header 。

#!/usr/bin/env python

import cgitb
import subprocess
import sys

cgitb.enable()

sys.stdout.write("Content-type: text/plain\r\n\r\n")

p = subprocess.Popen("/usr/games/fortune",stdout=subprocess.PIPE)
data = p.stdout.read()
p.wait()

print data

关于c++ - 通过 CGI python 脚本在服务器端运行 .exe 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15245242/

相关文章:

C++ 清除结构 vector 异常

python - Django 默认管理中的 LDAP

javascript - 在 Canvas 上,有什么方法可以让多个苹果在游戏中掉落?

c++ - vector 到循环中的数组不起作用

c++ - Mathematica/CUDA 减少执行时间

具有自行设计的有理数对类的 C++ 程序未按预期工作

python - Python Twisted Push Producer 不规则传输问题

Python 无法加载由 json.dump 创建的 JSON

javascript - 应该在这里使用 !important 吗?

html - 如何通过在 div 绝对位置使用高度 100% 来显示完整图像高度?