我有一个 C 代码,它将一个文件作为输入,对其进行处理并给出一个数字作为输出。我想构建一个 html 网页,它将文件路径作为输入,并将其提供给 C 代码。 C 代码对其进行处理并在浏览器中显示输出(整数)。你能建议我该怎么做吗?是否有任何预构建的软件可以执行此操作?
最佳答案
如果 C 代码用于生成命令行实用程序,那么您可以在生成网页时调用它:
#!/usr/bin/env python
import subprocess
from bottle import request, route, run, template # http://bottlepy.org/
command = ['wc', '-c'] # <-- XXX put your command here
@route('/')
def index():
filename = request.query.filename or 'default' # query: /?filename=<filename>
output = subprocess.check_output(command + [filename]) # run the command
return template("""<dl>
<dt>Input</dt>
<dd>{{filename}}</dd>
<dt>Output</dt>
<dd>{{output}}</dd></dl>""", filename=filename, output=output)
run(host='localhost', port=8080)
运行此脚本或将其粘贴到 Python 控制台中,然后打开浏览器并传递文件名(服务器上的路径)作为查询参数:
$ python -mwebbrowser http://localhost:8080/?filename=/etc/passwd
wc -c
打印每个输入文件的字节数。它在服务器上执行。
如果 C 代码可作为库使用;你可以使用 ctypes
module从 Python 调用 C 函数,例如从 libc
库调用 printf()
C 函数:
#!/usr/bin/env python
import ctypes
from ctypes.util import find_library
try:
libc = ctypes.cdll.msvcrt # Windows
except OSError:
libc = ctypes.cdll.LoadLibrary(find_library('c'))
n = libc.printf("abc ")
libc.printf("%d", n)
关于html - 创建一个网页来演示 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21876969/