【问题标题】:How to input data from a web page to Python script most efficiently如何最有效地将网页中的数据输入 Python 脚本
【发布时间】:2011-12-29 12:56:33
【问题描述】:

如何最轻松地从网页输入数据并将其传递给 Python 脚本?

我在这里和其他论坛上阅读了很多关于 Python 与 php 或 cgi,甚至 Tornado、Django 等相关的内容,但我很困惑什么是最适合我的解决方案。

我有一个 Python 脚本,它可以从网络上抓取数据、生成 .html 页面等 - 运行时只有一个

userIn=str(raw_input())

这使脚本根据终端中的输入收集数据。我现在只希望这个输入来自某种形式

<html>
<body>

<form action="test.php" method="get">
Name <input type="text" name="name" />
<input type="submit" />
</form>

</body>
</html> 

在文件 test.php 中,我尝试以任何形式(proc_open、exec...)传递值,但我似乎没有得到 python 和这种形式之间的联系,除此之外,我不确定是什么将 python 的输出(一些调试错误等)传递回 Web 界面的最佳方法是什么?!

非常感谢!

【问题讨论】:

    标签: php python forms cgi web


    【解决方案1】:

    我现在使用 exec() 命令管理它。

    <html>
    <body>
    
    <form action="test.php" method="get">
    <input type="text" name="name" />
    <input type="submit" />
    </form>
    
    </body>
    </html> 
    

    test.php:

    <?php
    exec("python mypythonscript.py ".$name, $output);
    ?>
    

    【讨论】:

    • 您可能想要使用escapeshellarg($name)implode(' ', array_map('escapeshellarg', explode(' ', $name))) 而不仅仅是$name。请参阅php.net/escapeshellarg 了解更多信息。
    【解决方案2】:

    要从表单中获取值,您可以将 action="test.php" 更改为 action="/where_you_hooked_your_webapp"

    应用程序的代码可以是:

    from flask import Flask, render_template, request
    
    app = Flask(__name__)
    
    @app.route('/')
    def handle_input():
        userIn = request.args.get('name', 'default name goes here')
        # grab data from the web, prepare data for html template, etc
        return render_template('user.html', user=userIn, data=data)
    

    要了解如何部署它,请参阅Flask Quickstart,例如Apache with mod_wsgi

    【讨论】:

    • 我只是在一个简单的设置中尝试了这个,但是在单击提交按钮时,我在 Firefox 中获得了 openfile-dialogue(...您选择打开 test.py 这是一个 python 脚本.. ... Firefox 应该如何处理这个文件?)...
    • @user1016690:你使用什么网络服务器?
    • @user1016690:按照我上面提供的"Apache with mod_wsgi" 链接中的说明进行操作。如果需要,安装mod_wsgi。对于调试,您可以简单地将上述应用程序作为脚本运行(只需在末尾添加app.run()),而无需任何外部网络服务器。
    【解决方案3】:

    为此使用 php passthru() 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多